OLi
OLi

Reputation: 11

android - how can i get a reference to the top level view to set an onTouch event?

could you please help me out or give me an example of the code i'd need to set a onTouchListener for an activity so when touched the activity will start a new activity? Just don't know how to do this and would like to see the code so I can make mine work

Thank you very much

Upvotes: 0

Views: 1968

Answers (2)

Peri Hartman
Peri Hartman

Reputation: 19484

Try this:

protected void onCreate(Bundle savedInstanceState) 
{
  super.onCreate(savedInstanceState);

  LayoutInflater inflater = getLayoutInflater();
  ViewGroup layout = (ViewGroup)inflater.inflate (R.layout.main_activity, null);
  setContentView (layout);
  ...
}

Upvotes: 0

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72331

In your layout.xml give an id to your root ViewGroup element let say 'RootView'. Then in your onCreate() method of your Activity you can get this view by calling:

     View root=findViewById(R.id.RootView);

and then you can set your OnTouchListener:

     root.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            startActivity(new Intent(CurrentActivity.this, MyNewActivity.class));
            //return true, the event was consumed
            return true;
        }
    });

Upvotes: 2

Related Questions