Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 529
Androider Avatar asked Mar 11 '11 22:03

Androider


People also ask

Why do we need to call setContentView () in onCreate () of activity class?

onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.

What does finish () do in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

Can we create activity without UI in Android?

Explanation. Generally, every activity is having its UI(Layout). But if a developer wants to create an activity without UI, he can do it.


2 Answers

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;

                                    }
                                });
like image 29
Patricia Avatar answered Sep 30 '22 20:09

Patricia


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( ...
like image 174
Matthew Willis Avatar answered Sep 30 '22 18:09

Matthew Willis