piyo_kuro
piyo_kuro

Reputation: 105

Detecting Single Tap in Screen for Android

i want to add a code where when a user tap the screen in his/her screen in android, there will be some dialog box showing that the screen is tapped. i tried few codings but it makes my project crash. any suggestions for coding? thank you.

Upvotes: 0

Views: 222

Answers (2)

Víctor Albertos
Víctor Albertos

Reputation: 8293

Implement on the root view an OnClickListener interface.

//TestActivity

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();
    }

}

//Layout

<?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>

Upvotes: 1

Nabin
Nabin

Reputation: 11776

Use onInterceptTouchEvent() method.

From documentation

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. 

Example:

Upvotes: 1

Related Questions