Android 之触屏事件

泄露秘密 提交于 2019-12-26 23:53:59

1.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"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="#D8BFD8"
        android:id="@+id/te"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:textSize="20dp"
        />

</LinearLayout>

MainActivity.java

package demo.com.chuping;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String TAG = "TEST";
    TextView textView;
    TextView show;

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

        textView = findViewById(R.id.te);
        show = findViewById(R.id.show);

        textView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if(event.getAction()==MotionEvent.ACTION_MOVE){
                       float x = event.getX();
                       float y = event.getY();
                       show.setText("X="+x+"  y="+y+"");
                }

                return true;
            }
        });
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN://按下
                Log.d(TAG,"按下");
                break;
            case MotionEvent.ACTION_MOVE: //移动
                Log.d(TAG,"移动");
                break;
            case MotionEvent.ACTION_UP: //抬起
                Log.d(TAG,"抬起");
                break;
            default:
                break;
        }


        return super.onTouchEvent(event);

    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!