如何检测Android上的触摸输入

Ryo*_*far 15 events android input touch

现在我所要做的就是检测屏幕被按下的时间,然后显示一条日志消息以确认它发生了.到目前为止我的代码是从CameraPreview示例代码修改的(它最终会拍照)所以大部分代码都在扩展SurfaceView的类中.SDK中示例代码的API为7.

Dar*_*ski 27

请尝试以下代码来检测触摸事件.

mView.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //show dialog here
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

要显示对话框,请使用Activity方法showDialog(int).你必须实现onCreateDialog().请参阅文档了解详细信


MSA*_*MSA 16

这是一个简单的例子,说明如何检测简单的触摸事件,获取坐标并显示祝酒词.这个例子中的事件是Action Down,Move和Action up.

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

public class MainActivity extends Activity {

    private boolean isTouch = false;

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int X = (int) event.getX();
        int Y = (int) event.getY();
        int eventaction = event.getAction();

        switch (eventaction) {
            case MotionEvent.ACTION_DOWN:
                Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                isTouch = true;
                break;

            case MotionEvent.ACTION_MOVE:
                Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                break;

            case MotionEvent.ACTION_UP:
                Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)


Som*_*ere 6

我是这样做的:

public class ActivityWhatever extends Activity implements OnTouchListener
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayout);

        //the whole screen becomes sensitive to touch
        mLinearLayoutMain = (LinearLayout) findViewById(R.id.layout_main);
        mLinearLayoutMain.setOnTouchListener(this);
    }

    public boolean onTouch(View v, MotionEvent event)
    {
        // TODO put code in here

        return false;//false indicates the event is not consumed
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图的 xml 中,指定:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/layout_main">

    <!-- other widgets go here-->

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)