Chap7. 인터페이스 기초04- 이벤트 (Event)
패키지명 : chap7_prac3
화면을 터치하면 메소드 재정의(onTouchEvent)를 통한 이벤트 처리
화면을 터치하고 있으면 layout의 textView가 "Layout Touch Down"
화면에서 손을 떼면 layout의 textView가 "Layout Touch Up"
버튼을 누르면 위젯 이벤트 처리
package ddwucom.mobile.chap7_prac3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConstraintLayout layout = findViewById(R.id.layout);
final TextView textView = findViewById(R.id.textView);
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
textView.setText("Layout Touch Down");
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
textView.setText("Layout Touch Up");
}
return false;
}
});
}
// 메소드 재정의
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(this, "메소드 재정의", Toast.LENGTH_SHORT).show();
return false;
}
// 위젯 이벤트 처리
public void onClick (View v) {
Toast.makeText(MainActivity.this, "위젯 이벤트 처리", Toast.LENGTH_SHORT).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:onClick="onClick"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>