-
[1] Touch EventDevelpment/Android Using Sample 2020. 9. 13. 21:34
1. Touch Event
Layout
123456<TextViewandroid:id="@+id/text_view"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:textSize="20dp" />cs * Layout에 TextView 생성 및 id 등록
Activity
12345678910111213141516171819202122public class MainActivity extends AppCompatActivity {TextView text_view;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);text_view = (TextView) findViewById(R.id.text_view);text_view.setOnTouchListener( touch );}View.OnTouchListener touch = new View.OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent motionEvent) {return true;}};}cs * TextView 객체 생성 및 Layout의 TextView와 연결.
* TouchListener 등록.
2. Listener 에서 Touch 이벤트 구분
OnTouchListener
1234567891011121314151617View.OnTouchListener touch = new View.OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent motionEvent) {switch( motionEvent.getAction() ){case MotionEvent.ACTION_DOWN:break;case MotionEvent.ACTION_UP:break;case MotionEvent.ACTION_MOVE:break;}return true;}};cs * TouchListener에서는 motionEvent의 값으로 Event 감지.
* return 값이 false일 경우 ACTION_DOWN 만 감지 가능.
3. Touch 정보 처리 방법
OnTouchListener
1234567891011121314151617181920212223242526View.OnTouchListener touch = new View.OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent motionEvent) {String result = "";int x = 0, y = 0;switch( motionEvent.getAction() ){case MotionEvent.ACTION_DOWN:text_view.setText("Action Down");break;case MotionEvent.ACTION_UP:text_view.setText("Action Up");break;case MotionEvent.ACTION_MOVE:x = (int)motionEvent.getX();y = (int)motionEvent.getY();result = String.format("x 좌표 : %d, y 좌표 : %d", x, y);text_view.setText(result);break;}return true;}};cs 4. 결과 화면
'Develpment > Android Using Sample' 카테고리의 다른 글
[5] Image Button Effect (drawable) (0) 2020.09.13 [4] Custom Button (0) 2020.09.13 [3] ListView (0) 2020.09.13 [2] Inflater (0) 2020.09.13 [0] Button Event (0) 2020.09.13