在操作栏swipeable标签与片段在运行时如何动态地设置数量 [英] How to dynamically set number of swipeable tabs in Action Bar with Fragments at runtime
问题描述
我指的这个链接swipeable利用碎片标签的。它为我工作,但如果我需要动态和不添加标签的数量pre指定标签的数量?举例来说,我的一些逻辑,让我有时2串anarray,有时4字符串数组输出。而根据逻辑我需要设置的选项卡中的操作栏在运行时的数量。我怎样才能做到这一点?谁能告诉我如何实现我需要什么?
I am referring this link for swipeable tabs using fragments. It worked for me, but what if I need to add the number of tabs dynamically and not pre assign the number of tabs? For instance, some of my logic gives me output at times 2 strings in anarray and at times 4 strings in an array. And according to the logic I need to set the number of tabs in action bar at runtime. How can I achieve this? Can anyone show me how to achieve what I need?
推荐答案
步骤1:
定义你的 TabsPagerAdapter
如下:
public class TabsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> list;
public TabsPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int index) {
return list.get(index);
}
@Override
public int getCount() {
return list.size();
}
}
第2步:
当你确定标签在运行时的数量,首先要确保创建一个列表
片段$ C $所需数量C>秒。你可以用它做任何的这个的:
When you determine the number of tabs at runtime, first make sure to create a List
of the required number of Fragment
s. You can do it using either this:
ArrayList<Fragment> list = new ArrayList<Fragment>();
for(int i = 0; i < tabcount; i++){
list.add(MyFragment.newInstance());
}
或 这个的:
ArrayList<Fragment> list = new ArrayList<Fragment>();
list.add(new GamesFragment());
list.add(new TopRatedFragment());
list.add(new MoviesFragment());
第三步:
当你创建一个适配器
为 ViewPager
,通过的ArrayList $ C $ç
片段>
S在的构造函数 TabsPagerAdapter
:
When you create an Adapter
for the ViewPager
, pass the ArrayList
of Fragment
s in the constructor of TabsPagerAdapter
:
TabsPagerAdapter adapter = new TabsPagerAdapter(fm, list);
试试这个。这将工作。
Try this. This will work.
这篇关于在操作栏swipeable标签与片段在运行时如何动态地设置数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!