从ViewPager和TabLayout Android中删除Tab片段

时间:2018-06-14 23:09:23

标签: android android-fragments android-viewpager recycler-adapter android-tablayout

我有一个活动,通过viewpager和片段托管tablayout。我已成功设置tablayout和viewpager,其中包含来自本地数据库的用户填充值,如下面的代码(试图简短,只显示一个选项卡) -

public void setUpTabs() {
   setUpViewPager(viewPager);
   tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
   tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
   tabLayout.setupWithViewPager(viewPager);
}

private void setUpViewPager(ViewPager viewPager) {

  Customize customize = new Select()  
          .from(Customize.class)
          .where("tabName = ? ", Constants.NATURE)
          .executeSingle();
  if (customize != null) {
      String nature = customize.tabName;
      Log.d(TAG, "Nature Tab Name:\t" + nature);
  }

  pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
  pagerAdapter.addTab(new Top30Fragment(), Constants.Top30); // default tab

  if (nature != null) {
      pagerAdapter.addTab(new NatureFragment(), Constants.NATURE); // dynamic tab from db
  }

  pagerAdapter.addTabAtLastPosition(new PrefsFragment(), Constants.PREFS);

  viewPager.setAdapter(pagerAdapter); 
  }

Customize是模型类,我使用ActiveAndroid库进行持久化。这是我的tabsadapter类代码:

public class TabsPagerAdapter extends FragmentPagerAdapter {

private static final String TAG = TabsPagerAdapter.class.getSimpleName();
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> titlesList = new ArrayList<>();

private ViewPager viewPager;
private TabLayout tabLayout;

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    return fragmentList.get(position);
}

@Override
public int getCount() {
    return fragmentList.size();
}

public void addTab(Fragment fragment, String name){
     fragmentList.add(fragment);
     titlesList.add(name);
}

public void addTabAtLastPosition(Fragment fragment, String name){
     fragmentList.add(fragmentList.size(), fragment);
     titlesList.add(name);
}

public void removeTab(Fragment fragment, String name){ //Not working
     for (int i = 0; i < fragmentList.size(); i++){
         if (fragmentList.get(i).equals(fragment)){ // never enters/returns from this loop
              Log.d(TAG, "Fragment at position:\t" + i);
              fragmentList.remove(fragment);
              titlesList.remove(name);
           }
      }
 }

 @Nullable
 @Override
 public CharSequence getPageTitle(int position) {
     return titlesList.get(position);
 } 
 }

在我的首选项片段(也是tablayout的一部分)中,我有一个带有复选框的recyclelerview,case1:如果选中,则在db中检查选项卡,如果尚未添加到tablayout,则仅添加到tablayout。 case2:否则,如果未选中,则表示选项卡处于布局和数据库中,必须从两者中删除。

我已经开始处理案例2,但我只能从db中删除值,要删除的选项卡仍然存在于tablayout中。这是我的recyclerview适配器代码,用于删除选项卡:

public class PrefsAdapter extends RecyclerView.Adapter<PrefsCustomizeViewHolder> {

private static final String TAG = PrefsAdapter.class.getSimpleName();

private final Context context;
private List<Customize> itemsList;

private long id_nature, id_space, id_seasons, id_art, id_scifi, id_misc;
private Customize cust; // Model class for saving and retrieving tabs

private TabsPagerAdapter pagerAdapter;
private String nature, space, seasons, art, scifi, misc;
private String tabNature, tabSpace, tabSeasons, tabArt, tabScifi, tabMisc;

public PrefsAdapter(Context context, List<Customize> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
    pagerAdapter = new TabsPagerAdapter(((AppCompatActivity)context).getSupportFragmentManager());
}

@Override
public PrefsCustomizeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prefs_customize_items_layout, parent, false);
    return new PrefsCustomizeViewHolder(view);
}

@Override
public void onBindViewHolder(final PrefsCustomizeViewHolder viewholder, final int position) {
  final Customize customize = itemsList.get(position);

  Picasso.with(context)
          .load(customize.getIcon())
          .fit()
          .into(viewholder.prefsSelImg);

         // search db to find if checkbox is checked, i.e tab is present or not and update recyclerview
  switch (position) {
      case 0:
          cust = new Select()
                  .from(Customize.class)
                  .where("tabName = ? ", Constants.SPACE)
                  .executeSingle();
          if (cust != null) {
              space = cust.tabName;
              Log.d(TAG, "Space Tab From DB:\t" + space);
              id_space = cust.getId();
              Log.d(TAG, "Space Tab Id from DB:\t" + id_space);
              viewholder.prefsCheckBox.setChecked(true);
           } else {
              viewholder.prefsCheckBox.setVisibility(View.INVISIBLE);
              viewholder.prefsCheckBox.setChecked(false);
           }
           break;
   }

   viewholder.prefsSelImg.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
          switch (position) {
              case 0:
                  if (viewholder.prefsCheckBox.isChecked()){
                      viewholder.prefsCheckBox.setChecked(false);

                      Customize.delete(Customize.class, id_space);
                      Log.d(TAG, "Deleted Space id:\t" + id_space); // prints right log detail
                      pagerAdapter.removeTab(new SpaceFragment(), Constants.SPACE);

                   } else {
                      viewholder.prefsCheckBox.setChecked(true);

                      customize.setTabId(UUID.randomUUID().toString());
                      customize.setTabName(Constants.NATURE);
                      customize.save();

                      pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);

                      viewholder.prefsCheckBox.setVisibility(View.VISIBLE);
                   }
                  break;
           }

        }
    });

}

@Override
public int getItemCount() {
    if (itemsList == null) {
       return 0;
    }
     return itemsList.size();
 }

}

tabspagerAdapter.removeTab()永远不会被调用,即使我已经在构造函数中初始化它,如下所示:

public PrefsAdapter(Context context, List<Customize> itemsList) {
this.context = context;
this.itemsList = itemsList;
pagerAdapter = new TabsPagerAdapter(((AppCompatActivity)context).getSupportFragmentManager());
} 

有人可以帮助我删除片段,以及为什么永远不会调用pagerAdapter.removeTab(fragment, title)方法以及如何更新标签布局。感谢。

1 个答案:

答案 0 :(得分:0)

我使用以下代码成功更改了标签数量(添加和删除)。我发现我必须从寻呼机适配器和标签布局中删除它们。

int cnp = mPagerAdapter.getCount();

// remove all tabs (or just the ones you need to remove) 
// from both the pager adapter and the tab layout
for(int i = cnp-1; i >= 0; --i) {
    mPagerAdapter.destroyItem(mViewPager, i, mPagerAdapter.getItem(i));
    mTabLayout.removeTabAt(i);
}

// add back in whatever tabs you need and update the pager adapter to be consistent
mTabLayout.addTab(mTabLayout.newTab().setText("Tab 0"),0);
mTabLayout.addTab(mTabLayout.newTab().setText("Tab 1"),1);
mPagerAdapter.setConfiguration(2); // my custom method to tell it which pages to show

mTabLayout.invalidate();
mPagerAdapter.notifyDataSetChanged();

相关班级成员:

ViewPager mViewPager;
TabLayout mTabLayout;
MyPagerAdapter mPagerAdapter; // extends FragmentPagerAdapter