티스토리 뷰

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_bright" />

    <View
        android:id="@+id/view2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_dark" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@android:color/background_dark"
            android:textSize="16dp" />
    </ScrollView>

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/my_selector"
        android:ems="10"
        android:inputType="text"
        android:text="" />
</LinearLayout>

 

my_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--selector: 어떤 상태에 따라서 거기에 drawble 같은걸 보여주는거-->
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/red" />
    <item
        android:drawable="@drawable/blue"/>
</selector>

 

MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    GestureDetector detector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);

        View view = findViewById(R.id.view);
        view.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event){
                int action = event.getAction();

                float curX = event.getX();
                float curY = event.getY();

                if(action==MotionEvent.ACTION_DOWN){
                    println("손가락 눌렸음 : "+curX+", "+curY);
                }else if(action == MotionEvent.ACTION_MOVE){
                    println("손가락 움직임 : "+curX+", "+curY);
                }else if(action==MotionEvent.ACTION_UP){
                    println("손가락 떼졌음 : "+curX+", "+curY);
                }
                return true;
                //메소드가 잘 실행되었음을 리턴
            }
        });

        detector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                println("onDown() 호출됨.");
                return true;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                println("onShowPress() 호출됨.");
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                println("onSingleTapUp() 호출됨.");
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                println("onScroll() 호출됨 : "+distanceX+", "+distanceY);
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                println("onLongPress() 호출됨.");
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                println("onFling() 호출됨 : "+velocityX+", "+velocityY);
                return true;
            }
        });

        View view2 = findViewById(R.id.view2);
        view2.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event){
                detector.onTouchEvent(event);
                return true;
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Toast.makeText(this,"시스템 BACK 버튼 눌림.", Toast.LENGTH_LONG).show();

            return true;
            //여기서 리턴 true 처리 돼서 back 키 눌러도 앱이 종료 안되고 단순 토스트만 날아옴
        }
        return false;
    }

    public void println(String data){
        textView.append(data + "\n");
    }
}

 

 

 

setOnTouchListener

첫번째 뷰(하늘색)에 onTouch 메소드를 걸어서 해당 하늘색 뷰를 눌렀을 때 / 누른 상태로 움직였을 때 / 손가락 땠을 때를 각각 전달받아 제일 밑 텍스트뷰에 이벤트와 좌표를 출력한다.(main.java에서 println( ) 메소드로 전달하여 구현함)

 

GestureDectector

또 안드로이드에는 GestureDectector 라고 사용자의 제스처를 구분해주는 인터페이스가 있는데

위 main.java 코드에 나와있는 메소드들이 있다. 그 중 onFling( )은 사용자가 터치 후 튕길 때에 해당하는 제스처!

그래서 GestureDectector는 온터치 리스너 기반으로 되어있고, 나의 예처럼 어떤 뷰에 걸어줄 때 setOnTouchListener-onTouch-onTouchEvent의 과정으로 걸어준다.

해당 기능에 대해서 따로 캡쳐는 안 했지만, 하늘색 뷰에 걸어둔 이벤트처럼 제일 밑 텍스트뷰에 출력됨을 확인할 수 있게 된다.

 

키 이벤트

그리고 어플리케이션 전체에 onKeyDown으로 키 이벤트를 걸어줬다.

해당 기능에 따라 back키를 누르면 (디바이스에서) 토트 메시지로 "시스템 Back버튼 눌림" 이라고 나온다.

코드블럭 주석에도 써놨지만, return true를 해줘서 앱이 종료되는 것이 아니라 단순 토스트가 날라가만 한다.

 

사실 시스템 BACK 키에 이벤트를 걸고 싶으면 굳이 onKeyDown에서 KEYCODE로 지정해주는 것보다는

void onBackPressed() 메소드를 재정의 하면 된다.

 

 

 

selector.xml

이건 이제 셀렉터 xml 부분인데 맨 마지막 EditText에 백그라운드로 넣어줬다.

EditText니까 우선 텍스트 입력하면 저런 식으로 나오고,

그 EditText 부분을 누르고 있으면 (Pressed에 해당됨) xml의 알고리즘 상 저렇게 빨간 공으로 바뀐다.

댓글