如何添加标签&片段动态?
我的代码:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < 4; i++) {
adapter.addFrag(new TabFragment(), "Tab"+i);
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Tab Fragment
public class TabFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activty_listview,container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
假设我的标签名称是“Tab1,Tab2,Tab3” 如果我上面的话,如何根据数组动态添加标签,以及如何选项卡片段知道选择了哪个标签。
欢迎任何建议。
提前致谢:)
答案 0 :(得分:0)
mTabLayout = (TabLayout)rootView.findViewById(R.id.tab_layout);
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab1)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab2)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab3)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab4)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab5)));
mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager = (ViewPager)rootView.findViewById(R.id.pager);
mPagerAdapter = new PagerAdapter
(getActivity().getSupportFragmentManager(), mTabLayout.getTabCount());
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
您可以参考this链接