<이벤트 처리>
1. 이벤트 구동 방식
1) 터치하면 바로 처리됨 => 폴링(polling) 방식
2) 다른 작업을 하고 있을테니 터치하면 알려줌 => 이벤트 구동 (event-driven) 방식
2. 안드로이드에서 이벤트 처리 방법
1) 이벤트 처리 객체를 생성하여 컴포넌트에 등록
2) 뷰 클래스의 이벤트 처리 메소드를 재정의
- 버튼에 붙은 리스너 객체가 이벤트를 처리함
3) 이벤트 리스너 콜백 메서드 설명
=====================================================================================
- View.OnClickListener onClick() 사용자가 어떤 항목을 터치하거나 엔터키를 눌러서 선택하면 호출됨
- View.OnKeyListener onKey() 키를 눌렀다가 놓았을 때 호출됨
- View.OnTouchListener onTouch() 사용자가 터치 이벤트로 간주되는 동작을 한 경우에 호출됨
4) 리스너 객체를 생성하는 방법
- 리스너 클래스를 익명 클래스로 정의함 (가장 많이 사용되는 방법)
- 익명클래스 : 클래스 몸체는 정의되지만, 이름이 없는 클래스임
클래스를 정의하면서 동시에 객체를 생성하게 됨
<MainActivity.java>
package kr.co.ratingbarapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
final RatingBar ratingBar = findViewById(R.id.ratingbar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Toast.makeText(getApplicationContext(), "New Rating : " + v, Toast.LENGTH_SHORT).show();
}
});
}
}
<activity_main.xml>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingbar"
android:numStars="5"
android:stepSize="1.0"/>
</LinearLayout>
<결과 출력>
'App > Android Java' 카테고리의 다른 글
Android_Java(6) - VolumeControlView (0) | 2022.02.07 |
---|---|
Android_Java(5) - MyViewEvent (0) | 2022.02.07 |
Android_Java(3) - ImageView(pets) (0) | 2022.02.04 |
Android_Java(2) - 안드로이드 기본사항 (0) | 2022.02.04 |
Android_Java(1) - 개요 (0) | 2022.02.03 |
댓글