我有一个活动,我创建了一个包含两个片段的viewpager。我需要在活动中获取对现有片段或其视图的引用,以便在必要时从片段刷新列表。我正在寻找解决方案两天,但在这个场合什么也没找到。
所以这是我的适配器
public class SearchPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public SearchPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
@Override
public Fragment getItem(int position) {
if(position == 0)
{
FragmentAyahSearch tab1 = new FragmentAyahSearch();
return tab1;
}
else
{
FragmentSurahList tab2 = new FragmentSurahList();
return tab2;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
@Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
@Override
public int getCount() {
return NumbOfTabs;
}
}
下面,我在MainActivity中创建了一个viewpager和适配器
searchAdapter = new SearchPagerAdapter(getSupportFragmentManager(), searchTitles, Numboftabs);
pager.setAdapter(searchAdapter);
tabs.setViewPager(pager);
我希望你能帮助我,因为我对此失去了理智。
答案 0 :(得分:1)
I would suggest maintain a list like
private List<Fragment> frag = new ArrayList<Fragment>();
then
public class SearchPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public SearchPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
@Override
public Fragment getItem(int position)
{
Fragment fragment = frag.get(position);
if(fragment == null )
{
if (position == 0)
{
fragment = new FragmentAyahSearch();
}
else
{
fragment = new FragmentSurahList();
}
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
@Override
public int getCount() {
return frag.size();
}
now if you want the reference of any fragment
just call , frag.get(<position>) will return you desire frgament