Android How to register OnTouchEvent for entire Activity main content view?

31,508

Solution 1

If you're looking for a way to get your content view as a View after Activity#setContentView(int), then you can set an id on the outer-most element of your layout:

android:id="@+id/entire_view"

and reference it in your onCreate method after setContentView:

View view = getViewById(R.id.entire_view);
view.setOnTouchListener( ...

Solution 2

Like this (in onCreate):

setContentView(R.layout.activity_main);

View view = findViewById(R.id.main); 
view.setOnTouchListener(new View.OnTouchListener() {

                                    @Override
                                    public boolean onTouch(View view,MotionEvent event) {


                                        return true;

                                    }
                                });

Solution 3

Activities onCreate() method:

onCreate(){
  setContentView(R.id.yourMainLayout);
  View contentView = (View)findViewById(R.id.yourMainLayout);
  contentView.setOnTouchListener((View.OnTouchListener)this);
 }

Unless someone knows a better way.

Share:
31,508
Androider
Author by

Androider

Updated on July 09, 2022

Comments

  • Androider
    Androider almost 2 years

    I have implemented onTouchEvent(TouchEvent) on my activity. However, I would like to know what steps are required to register this as the event for the activities main Content view. I want to set the onTouchEvent for the view that covers the entire screen space of the activity. there is a setContentView() which takes a layout id. How do I register the activity as the ontouchEvent listener to the main content view. I am considering findByView(activityLayoutId) to get this view, but this does not seem quite like the right or best way. Thanks

  • Androider
    Androider about 13 years
    you might still use R.layout.yourMainLayout and within layout provide youMainLayout as id
  • Farid
    Farid over 2 years
    @Androider "I am just looking for how to activite touch event on whole activity screen, not on some view added to this screen." then why you accepted this answer?! this is still some view added to this activity.
  • Tob237
    Tob237 over 2 years
    Also make sure that the view is "clickable", if it is not that by default, you can simpy set the view to be "clickable" by setting android:clickable="true" on the view in the XML-file.