Call Fragment Function Over Activity
Solution 1:
You can access the desired fragment's method through your PagerAdapter:
((TabFragment1)adapter.getItem(0)).helloworld();
Solution 2:
It's a bit trickier than usual with ViewPager
s, because you can't use the preferred findFragmentByTag()
method. Here's something you could try - it's untested, but should be ok:
Create an interface, which all
Fragment
s in yourViewPager
implement:publicinterfaceViewPagerFragmentBase { voidcallCommonMethod(int code); }
Implement it in all your
ViewPager
Fragment
s:public FragmentOne implementsViewPagerFragmentBase { @OverridepublicvoidcallCommonMethod(int code) { if (code == 1) { //Run code in this Fragment } } public FragmentTwo implementsViewPagerFragmentBase { @OverridepublicvoidcallCommonMethod(int code) { if (code == 2) { //Run code in this Fragment } }
Inside your
Activity
class, grab allFragment
s currently in yourAdapter
, then cycle through each one, calling thecallCommonMethod()
along with a code which indicates theFragment
you are trying to reach:publicclassMainActivityextendsAppCompatActivity { privatevoidcallCommonMethodInFragments(int code) { for (inti=0; i < viewPagerAdapter.getCount(); i++) { ((ViewPagerFragmentBase)viewPagerAdapter.getItem(i)).callCommonMethod(code); } } //To call it... callCommonMethodInFragments(1); //This will run the method in FragmentOne only }
If the code matches the one in the Fragment
you are trying to reach, then the method will run.
Something else you could also try though is an EventBus
- this would allow you to achieve your goal more directly, and with less typing: https://github.com/greenrobot/EventBus
Solution 3:
To call fragment method from parent
activity:
ExampleFragmentfragment= (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.callFunction();
Solution 4:
I had the same issue, and this worked for me: You have to add the fragments via your adapter and then you can access the fragment functions:
myViewPager = (ViewPager) findViewById(R.id.viewpager);
MyAdapterClassadapter=newMyAdapterClass(getSupportFragmentManager());
adapter.addFragment(newTabOneFragment(), "");
adapter.addFragment(newTabTwoFragment(), "");
adapter.addFragment(newTabThreeFragment(), "");
myViewPager.setAdapter(adapter);
myTabLayout = (TabLayout) findViewById(R.id.tab_layout);
myTabLayout.setupWithViewPager(myViewPager);
// to access fragment functions:TabOneFragmenttabOneFragment= (TabOneFragment) adapter.getItem(0);
tabOneFragment.functionWhatSoEver();
Post a Comment for "Call Fragment Function Over Activity"