Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment activity catch onKeyDown and use in fragment

I have Fragment activity with pager:

List<Fragment> fragments = new Vector<Fragment>();     fragments.add(Fragment.instantiate(this, PastEventListFragment.class.getName(),bundle));     fragments.add(Fragment.instantiate(this, EventListFragment.class.getName(),bundle));      this.mPagerAdapter  = new EventPagerAdapter(super.getSupportFragmentManager(), fragments);     //     ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager1);      pager.setAdapter(this.mPagerAdapter);     pager.setCurrentItem(1); 

I catch onKeyDown event :

@Override public boolean onKeyDown(int keyCode, KeyEvent event) {     if (keyCode == KeyEvent.KEYCODE_MENU) {      }     return super.onKeyDown(keyCode, event); } 

The Question is: How to use event in all fragments i have instantiated in this activity . Thanks

like image 429
FlorinD Avatar asked Aug 31 '12 07:08

FlorinD


People also ask

Can fragments be used in multiple activities?

You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.

How do you load a fragment inside an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

Can you start an activity from a fragment?

If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .

Can fragments be used without an activity?

It can't exist independently. We can't create multi-screen UI without using fragment in an activity, After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity.


1 Answers

What you can do is to define a custom method in your fragment class(s). For example:

public void myOnKeyDown(int key_code){    //do whatever you want here } 

and call this method whenever a key-down event is raised in your Activity class. For example:

@Override public boolean onKeyDown(int keyCode, KeyEvent event) {     if (keyCode == KeyEvent.KEYCODE_MENU) {         ((PastEventListFragment)fragments.get(0)).myOnKeyDown(keyCode);         ((EventListFragment)fragments.get(1)).myOnKeyDown(keyCode);          //and so on...     }     return super.onKeyDown(keyCode, event); } 
like image 153
waqaslam Avatar answered Oct 09 '22 03:10

waqaslam