我正在使用我找到的代码here。
public class ActionBarTabs extends SherlockFragmentActivity {
CustomViewPager mViewPager;
TabsAdapter mTabsAdapter;
TextView tabCenter;
TextView tabText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mViewPager = new CustomViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Home"),
ToolKitFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText("FujiSan"),
FujiFragment.class, null);
}
public static class TabsAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
我正在尝试修改它,以便我可以动态删除标签。我试过简单地创建这个函数:
public void removeTab(ActionBar.Tab tab) {
mTabs.remove(tab);
mActionBar.removeTab(tab);
notifyDataSetChanged();
}
但我总是得到一个indexoutofboundsexception。有谁知道这样做的好方法?
修改
将我的方法改为:
public void removeTab(ActionBar.Tab tab) {
mTabs.remove(tab.getTag());
mActionBar.removeTab(tab);
notifyDataSetChanged();
}
我能够成功删除标签。但是,当我删除不是最右边的选项卡时,与选项卡关联的视图(或片段?)不会消失。相反,它似乎与下一个最高标签相关联。例如,如果我删除了选项卡0,则选项卡0的视图只会移动到选项卡1.如果我删除具有最高ID的选项卡,则选项卡和视图会正确消失,但在添加新选项卡时会返回。
好像有一个与选项卡关联的片段列表,删除选项卡不会删除片段。有没有人知道造成这种情况的原因是什么?
EDIT2
我试图用以下内容删除片段:
Fragment fragmentToRemove = getItem(tab.getPosition());
destroyItem(mViewPager, tab.getPosition(), fragmentToRemove);
以及
Fragment fragmentToRemove = getItem(tab.getPosition());
FragmentTransaction fragmentTransaction = mActivity
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(fragmentToRemove);
fragmentTransaction.commit();
但迄今为止都没有奏效。
答案 0 :(得分:8)
知道了!
public void removeTab(ActionBar.Tab tab) {
mTabs.remove(tab.getTag());
mActionBar.removeTab(tab);
notifyDataSetChanged();
}
并覆盖destroyItem
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
super.destroyItem(container, position, object);
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
完美的工作!!!
答案 1 :(得分:5)
我今天刚刚发现支持插入或删除标签的真正技巧是覆盖FragmentPagerAdapter.getItemPosition()
:
@Override
public int getItemPosition(Object object) {
Fragment fragment = (Fragment) object;
for (int i = 0; i < tabInfos.size(); i++) {
if (tabInfos.get(i).clss == fragment.getClass()) {
return i;
}
}
// The tab must have been removed
return POSITION_NONE;
}
在调用getItemPosition()
(添加/删除标签后)后,ViewPager
将调用 notifyDataSetChanged()
。 ViewPager
正在尝试使用此适配器重新同步其缓存。它为它所拥有的每个“对象”(片段)调用getItemPosition()
,并告诉它片段来自哪个位置。如果没有匹配,那是因为我们删除了该标签,因此请返回POSITION_NONE
。
我还发现,如果插入或删除标签,则覆盖FragmentPagerAdapter.getItemId()
很重要,因为片段将左右移动位置。此方法由FragmentPagerAdapter.instantiateItem()
调用,并附加到项目的名称(String)。它使用此名称查找具有匹配名称(如果有)的预先存在的片段,否则将实例化新的片段。这是一些代码:
@Override
public long getItemId(int position) {
TabInfo info = tabInfos.get(position);
// The default hashCode() implementation is based on memory address, which will be unique
int hash = info.clss.hashCode();
return hash;
}
答案 2 :(得分:0)
好-这个人吃了我的午餐两周了。我没有发现上述内容对我完全适用。万一重要,我正在使用Android Studio 3.5.1。
接下来是我的FragmentPagerAdapter代码的全部内容。它包含您需要的大部分内容。无论您的每个片段包含什么,片段代码都非常简单。但是,如果需要更多信息或有任何疑问,请告诉我。
此外,如果您有任何评论或发现任何错误,请发表评论。我希望这对其他人有帮助。
import android.content.Context;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
public class ChecklistPagerAdapter extends FragmentPagerAdapter {
private final Context mContext;
private int currentTabPosition = -1;
ArrayList<String> tabNames = new ArrayList<>();
ArrayList<Fragment> fragments = new ArrayList<>();
public ChecklistPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public void add(Fragment fragment, String title) {
tabNames.add(title);
fragments.add(fragment);
}
public int getCurrentTabPosition() {
return currentTabPosition;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getItemPosition(@NonNull Object object) {
ChecklistFragment fragment = (ChecklistFragment) object;
for (int i = 0; i < fragments.size(); i++) {
if (fragments.get(i).equals(fragment)) {
return i;
}
}
return POSITION_NONE;
}
@Override
public long getItemId(int position) {
return fragments.get(position).hashCode();
}
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
super.setPrimaryItem(container, position, object);
currentTabPosition = position;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return tabNames.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
public void removeTab(TabLayout tabLayout, ViewPager viewPager, DBHelper dbHelper) {
// Get current tab position as it changes below
int position = currentTabPosition;
// Get current fragment representing curTab
ChecklistFragment fragment = (ChecklistFragment) fragments.get(position);
// Remove Tab
tabLayout.removeTabAt(position);
// Remove from ArrayLists
fragments.remove(position);
tabNames.remove(position);
// Remove fragment
FragmentManager fragmentManager = fragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
// Refresh
tabLayout.invalidate();
notifyDataSetChanged();
// Remove all records from ChecklistTab table
dbHelper.clearChecklistTab(fragment.getOutingId(), fragment.getChecklistId());
}
}