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
If someone is interessed how to do it with Boradcast:
In your fragment in onViewCreated
your keyevent - code to put in activity
your broadcast sender:
I've subclassed Activity and Fragment classes to perform KeyEvents passing. For me, it looks clearer than sending local broadcasts. But this solution can be not so flexible. Choose the preferred way by yourself.
Here is the activity:
And the fragment:
Gist: https://gist.github.com/0neel/7d1ed5d26f2148b4168b6616337159ed
As mentioned by others, the accepted answer results in tight coupling between the activity and its fragments.
I would suggest using some sort of event-based implementation instead. This is much more reusable and results in a better software architecture. In previous projects I have used one of the following solutions (Kotlin):
Broadcasts
Using Android´s LocalBroadcastManager: Documentation
Create a BroadcastReceiver:
}
In your activity:
Then, in any of the fragments (or services, etc..):
EventBus
Using EventBus
Create an event class:
In your activity:
Then, in your fragment:
What you can do is to define a custom method in your fragment class(s). For example:
and call this method whenever a key-down event is raised in your Activity class. For example: