在Android屏幕中检测单击

时间:2014-09-14 17:19:43

标签: android eclipse

我想添加一个代码,当用户点击他/她在Android屏幕中的屏幕时,会出现一些对话框显示屏幕被点击。我尝试了很少的编码,但它让我的项目崩溃了。任何编码建议?谢谢。

2 个答案:

答案 0 :(得分:1)

使用onInterceptTouchEvent()方法。

来自文档

Implement this method to intercept all touch screen motion events. 
This allows you to watch events as they are dispatched to your children,
and take ownership of the current gesture at any point. 

示例:

答案 1 :(得分:1)

在根视图上实现OnClickListener接口。

//测试活动

public class TestActivity extends Activity {

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

        findViewById(R.id.ll_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });

    }

    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Screen tapped")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

}

//布局

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

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

</LinearLayout>