我有一个程序,它有片段作为arraylist,我正在使用它与TabLayout,因为我删除一个选项卡我也想删除片段。但是我的实现并不顺序。标签1将删除Fragment2等。请检查我哪里出错?
在onCreate of MainActivity下,这就是我添加片段的方式
private TabPagerAdapter pagerAdapter;
public List<Fragment> fragmentList = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
fragmentList.add(NewsFragment.newInstance(Tab1));
fragmentList.add(NewsFragment.newInstance(Tab2));
fragmentList.add(NewsFragment.newInstance(Tab3));
mViewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), fragmentList);
mViewPager.setAdapter(pagerAdapter);
这是我的FragmentStatePagerAdapter,removeFragment是我试图删除片段的地方
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList;
private List<String> tabTitles = new ArrayList<>();
@Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
mFragmentList = fragmentList;
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void removeFragment(int tabPosition) {
if (!mFragmentList.isEmpty()) {
mFragmentList.remove(tabPosition);
}
}
}
主要活动下的OnActivity结果是我试图删除选项卡&amp;片段
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK || data == null)
return;
settingList = (ArrayList<SettingCheckBox>) data.getSerializableExtra(SETTING_CHECK_BOX);
for (int i = 0; i < settingList.size(); i++) {
if (settingList.get(i).getChecked()) {
Log.d("**Checked Item**", String.valueOf(settingList.get(i).getDescription()));
String removeTab = String.valueOf(settingList.get(i).getDescription());
Boolean checkedValue = settingList.get(i).getChecked();
if (removeTab.equals("tab1")) {
//remove tab
tabLayout.removeTab(tab1);
//remove fragment
pagerAdapter.removeFragment(0);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
} else if (removeTab.equals("tab2")) {
tabLayout.removeTab(tab2);
pagerAdapter.removeFragment(1);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
} else if (removeTab.equals("tab3")) {
tabLayout.removeTab(tab3);
pagerAdapter.removeFragment(2);
// fragmentList.remove(i);
pagerAdapter.notifyDataSetChanged();
}
答案 0 :(得分:0)
更改您pagerAdapter.removeFragment(mViewPager.getCurrentItem()); to pagerAdapter.removeFragment(correctFragmentPosition);
correctFragmentPosition =根据removeTab
的值计算答案 1 :(得分:0)
回答我自己的问题。我以这种方式添加了片段
public List<Fragment> fragmentList = new ArrayList<>();
private NewsFragment frag1
frag1 = NewsFragment.newInstance("https://www.yahoo.com");
fragmentList.add(frag1);
如果我需要找到片段的位置
for (int i = 0; i < fragmentList.size(); i++) {
if (fragmentList.get(i).equals(frag1)) {
//found the position so removing it
pagerAdapter.removeFragment(i); }
}