我如何在 android 中使用 viewpager 创建动态选项卡?

How can i create dynamically tab with viewpager in android?

解释:

假设,我有多个类别来自我的 REST。我不知道有多少类别可能是 5,7 或有时是 2 等。我想用 viewpager 将所有类别放在我的选项卡上。我想根据类别大小创建一个选项卡。让我们看看例如假设在我的 REST 响应中只有 2 个类别,它只创建两个选项卡。如果它有 5 个类别,则有 5 个选项卡,依此类推。

这里是创建标签的示例测试示例。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout=(TabLayout)findViewById(R.id.tabs);
        viewPager=(ViewPager)findViewById(R.id.viewpager);

        setupViewPager(viewPager);
        viewPager.setCurrentItem(0);
        tabLayout.setupWithViewPager(viewPager);
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        for(int i=0;i<3;i++){
            adapter.addFragment(new OneFragment(), "ONE");
//            adapter.addFragment(new TwoFragment(), "TWO");
            viewPager.setAdapter(adapter);
        }
    }
}

ViewPagerAdapter.java

public 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 addFragment(Fragment fragment,String title){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

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

请问,我该如何解决???

如果我是你,我会尝试这样的事情:

它不是一个完美的解决方案,只是一个如何实现的想法,您需要进一步修改它。

创建number of fagments = total number of categeries并将它们命名为fragment0fragment1等以达到类别总数。

然后先得到类别的数量让我们说

int count = number of categeries;

然后像这样将片段添加到ViewPager

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    for(int i=0; i <= count; i++){
        adapter.addFragment(new Fragment(i)(), "ONE");
        viewPager.setAdapter(adapter);
    }
}

并命名片段,即标签标题,您可以制作片段标题列表,类似这样

private final String[] title = {"One", "Two","Three"};

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        for(int i=0; i < count; i++){
            adapter.addFragment(new Fragment(i)(), title[i]);
            viewPager.setAdapter(adapter);
        }
    }

希望对你有帮助

获得类别大小后,您可以根据类别大小添加动态标签,如下所示:

public class MainActivity extends AppCompatActivity {

TabLayout tabLayout;
ViewPager viewPager;
Toolbar toolbar;
int no_of_categories=-1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar=(Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    tabLayout=(TabLayout)findViewById(R.id.tabs);
    viewPager=(ViewPager)findViewById(R.id.viewpager);

    no_of_categories=YOUR_NO_CATEGORIES;

    for (int i = 0; i < no_of_weeks; i++) {
        tabLayout.addTab(tabLayout.newTab().setText("TAB " + String.valueOf(i + 1)));
    }

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
    viewPager.setAdapter(adapter);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });


   }
}

您的适配器 Class 应该如下所示:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    int mNumOfTabs;
    Fragment fragment = null;

    public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        for (int i = 0; i < mNumOfTabs ; i++) {
            if (i == position) {
                fragment = YourFragment.newInstance();
                break;
            }
        }
        return fragment;

    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return super.getPageTitle(position);
    }
}

对于 Kotlin

获得类别大小后,您可以根据类别大小添加动态标签,如下所示:

class CategoryActivity : AppCompatActivity() {

    lateinit var binding: ActivityCategoryBinding
    var numberOfCat: Int? = -1


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_category)

        numberOfCat = 10
        for (i in 0..numberOfCat!!){
            tabs_main.addTab(tabs_main.newTab().setText("Hello Fragment"))
        }
        var pagerViewAdapter = CategoryViewPagerAdapter(supportFragmentManager,tabs_main.tabCount,str)
        viewpager_main.adapter = pagerViewAdapter
        viewpager_main.adapter = pagerViewAdapter

        tabs_main.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener{
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                viewpager_main.currentItem = p0!!.position
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {

            }
        })

    }
}

这是你的适配器 class:

class CategoryViewPagerAdapter(fm: FragmentManager, numberOfTabs: Int, title: String): FragmentPagerAdapter(fm) {

    var fragment: Fragment? = null
    var noOfTabs: Int = numberOfTabs
    var title: String = title

    override fun getItem(position: Int): Fragment {
        for (i in 0..noOfTabs){
            if (i == position){
                fragment = CommonFragmentForCategory.newInstance(title = title)
                break
            }
        }
        return fragment!!
    }

    override fun getCount(): Int {
        return noOfTabs
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return super.getPageTitle(position)
    }
}

如果你想要动态的 tablayout 和 viewpager,你可以使用下面的 kotlin 代码;

  for (i in 0 until tabLayout.size) {
        tabLayout.addTab(tabLayout.newTab().setText(tablayoutNameHere))
    }

这个区域如果你想要不可滚动你可以使用它;

    var tabLayoutConfig = Runnable {
        if (tabLayoutPrivilege.width < resources.displayMetrics.widthPixels) {
            tabLayoutPrivilege.tabMode = TabLayout.MODE_FIXED
            val mParams = tabLayoutPrivilege.layoutParams
            mParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            tabLayoutPrivilege.layoutParams = mParams
        } else {
            tabLayoutPrivilege.tabMode = TabLayout.MODE_SCROLLABLE
        }
    }

    tabLayoutPrivilege.post(tabLayoutConfig)




val dynamicPrivilegeFragmentAdapter = DynamicPrivilegeFragmentAdapter(supportFragmentManager, tabCount,yourListHere)
        vpPrivilege.adapter = dynamicPrivilegeFragmentAdapter