Android Programming
[Mobile Programming] 이벤트 처리 실습
gangintheremark
2021. 10. 17. 06:01
728x90
실습내용
- 버튼 만들기
- 버튼을 클릭하면 바탕색 변경
XML코드에 이벤트에 따른 콜백함수 지정
//XML코드
<Button
android:id="@+id/button"
...
android:onClick="onbuttonclick" //위젯의 Click 이벤트에 콜백함수 onClickButton 지정
android:text="first method"
/>
//JAVA 코드
public class MainActivity extends AppCompatActivity {
Button btn;
protected void onCreate(Bundle savedInstanceState) {
...
btn = (Button)findViewById(R.id.button);
}
public void onbuttonClick(View v) { // onbuttonClick 함수 구현
v.setBackgroundColor(Color.YELLOW);
}
}
이벤트처리 객체를 통한 방법
<리스너 클래스를 내부 클래스로 정의>
//JAVA 코드
public class MainActivity extends AppCompatActivity { // 인터페이스를 구현한 클래스 정의
Button btn;
class myListener implements View.OnClickListener {
public void onClick(View target) {
target.setBackgroundColor(Color.RED);
}
}
protected void onCreate(Bundle savedInstanceState) {
...
myListener mils = new myListener(); // 이벤트 리스너 객체 생성
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(mils); //버튼에 이벤트 리스너 객체 등록
}
<리스너 클래스를 무명 클래스로 정의>
public class MainActivity extends AppCompatActivity {
Button btn;
protected void onCreate(Bundle savedInstanceState) {
...
btn = (Button)findViewById(R.id.button);
//클래스를 정의하면서 동시에 객체 생성
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setBackgroundColor(Color.YELLOW);
}
});
}
이벤트 처리 메소드를 재정의
OnTouchEvent(MotionEvent) 재정의 실습
public class MainActivity extends AppCompatActivity {
class MyCustomView extends View {
int x,y;
//생성자 ( 클래스와 같은 이름 )
public MyCustomView(Context mycon) {
super(mycon);
setBackgroundColor(Color.MAGENTA); // 생성자에서 미리 화면의 색 지정 가능
}
//이벤트처리함수 재정의
@Override // 재정의 표시
public boolean onTouchEvent(MotionEvent event) { // MotionEvent : 화면을 터치했을 때 터치한 지점에 대한 좌표값
x = (int)event.getX(0);
y = (int) event.getY(0)
invalidate();
return super.onTouchEvent(event); // boolean 값으로 return 하는 형태로 onTouchEvent 재정의
}
//화면에 그리는 그림
protected void onDraw(Canvas canvas) {
Paint mypaint = new Paint();
mypaint.setTextSize(50);
canvas.drawCircle(x,y,20,mypaint);
canvas.drawText("(" + x +", "+ y +") 에서 터치 발생",x,y+50,mypaint);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
MyCustomView w = new MyCustomView(this); // myCustomView에 대한 객체 만들기
setContentView(w);
}
}
728x90