zapotec
zapotec

Reputation: 2648

onTouchListener on several views

My problem is that I want to try to receive ANY TOUCH wherever is it on the screen. To do that, what I tohought is to create a layout with a main "RelativeLayout". The activity implements "onTouchListener". This is the layout I have:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/ic_launcher" /></RelativeLayout>

This is the code of my Activity:

public class MainActivity extends Activity implements OnTouchListener{

private Context context = null;
private ImageView imagen = null;

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

    imagen = (ImageView)findViewById(R.id.imageView1);
    imagen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    RelativeLayout relative = (RelativeLayout)findViewById(R.id.relative);
    relative.setOnTouchListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    Toast.makeText(context, "Touch!!", Toast.LENGTH_SHORT).show();
    return false;
}

The point is that if I touch the Image, it is not showing the toast(and I want to show the toast if you are touching wherever is it on the screen).

Anyone knows how can I receive the event of touching the screen on my Activity(wherever it is??).

EDIT: What I want is not a listener for the ImageView too, what I want is to know if there is a way to receive the event of the user touching the screen whatever it is there.

Thanks a lot!

Upvotes: 0

Views: 187

Answers (2)

faylon
faylon

Reputation: 7450

Since your ImageView is clickable, the touch event will be dispatched to the ImageView and the Activity cannot receive it. If you want to intercept all touch event before it is dispatched to view, you should override the Activity.dispatchTouchEvent(MotionEvent ev).

public boolean dispatchTouchEvent(MotionEvent ev) {
    // add your code here
    return super.dispatchTouchEvent(ev);
}

Upvotes: 1

Emile
Emile

Reputation: 11721

Try adding the touch listener to your image and not the main relative layout.

imagen.setOnTouchListener(this);

Upvotes: 0

Related Questions