tags:

views:

197

answers:

2

I want to detect when a user taps anywhere in a view in my Android application.

My code looks like this:

linearLayout = (LinearLayout) findViewById(R.id.linearLayout); // main layout
// ...
linearLayout.setOnTouchListener(this);
// ...
public boolean onTouch(View v, MotionEvent event) {
    Toast.makeText(this, "Touch!", 1000);
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        Toast.makeText(this, "Down!", 1000);
        return true;
    }
    return false;
}   

...but when I click on the view, I don't get Toast!

Do touch events work in the emulator -- or have I got something wrong in my code?

+6  A: 

I think the problem is with your message-displaying code rather than your touch-detecting code.

You're creating the Toast object but you're not displaying it. You need to call the show() method.

Also, the duration argument to the makeText() method should be one of LENGTH_SHORT or LENGTH_LONG.

Try:

Toast.makeText(this, "Down!", Toast.LENGTH_LONG).show();
Dave Webb
+1. I'm *always* forgetting to add `.show()` to my toasts!
Christopher
d'oh! + 1 vote + 1 tick + thanks x 2
Sam Dutton
We've all been there...well I have anyway...twice.
Tom R
A: 

I didnt try your c ode but i'd rather use onTouchEvent(MotienEvent e) witin the view class, it will work !

Vegas377