问题描述
我有一个活动,其中包含三个片段.这些片段通过PagerAdapter使用操作栏选项卡.我想做的是从主要活动中访问活动选项卡式片段中的方法.我已经尝试了下面的代码,但是这只是将片段返回为null,所以我想它在选项卡中找不到它!
I have one activity that comprises of three fragments. The fragments use the actionbar tabs using a PagerAdapter. What I want to do is access a method in the active tabbed fragment from the main activity. I have tried the below code but this just returns the fragment as null, so I guess it cant find it within the tabs!
NPListFragment articleFrag = (NPListFragment) getSupportFragmentManager().findFragmentByTag("NP");
articleFrag.refreshT();
PagerAdapter:
PagerAdapter:
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new NPListFragment();
case 1:
return new PListFragment();
case 2:
return new FavouritesFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}有人可以建议吗?我已经花了大约6个小时来解决这个问题,但是我并没有取得任何进展.
}Can anyone advise? I have spent about 6 hours on this, i'm just not making any progress resolving this.
推荐答案
您应该做的是:每个片段仅创建一次,然后将其用于对getItem方法的所有调用.
What you should do is : create only once each fragment and then give it for all calls to the getItem method.
例如:
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
Fragment one, two, three;
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
if(one == null)
one = new NPListFragment();
return one;
case 1:
if(two == null)
two= new PListFragment();
return two;
case 2:
if(three == null)
three= new FavouritesFragment();
return three;
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
现在,即使您在活动中,也可以呼叫 getItem
Now, even you in your activity you can call getItem
如果要调用特定方法,只需要将其转换为真实的片段类.
You'll just need to cast it to the real fragment class if you want to call a specific method.
int pos = viewpager.getCurrentItem();
Fragment activeFragment = adapter.getItem(pos);
if(pos == 0)
((NPListFragment)activeFragment).refreshT();
...
这篇关于从活动中调用选项卡式片段方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!