Fragment activity catch onKeyDown and use in fragment

FlorinD picture FlorinD · Aug 31, 2012 · Viewed 54.8k times · Source

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

Answer

waqaslam picture waqaslam · Aug 31, 2012

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);
}