How can i create dynamically tab with viewpager in android?

为君一笑 提交于 2020-01-01 02:11:14

问题


Explanation:

Suppose, I have multiple categories which come from my REST. I don't know how many categories it's mat be 5,7 or sometimes 2 etc. I want to put all the categories on my tab with viewpager. I want to create a tab accordingly to the categories size. let's see e.g. suppose in my REST response have only 2 categories it's create only two tab. if it have 5 categories then 5 tab and so on.

Here is the sample test example to create a tabs.

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);
    }
}

Please, How can I solve out???


回答1:


After you get categories size, you can add dynamic tabs as per your categories size as below:

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) {

        }
    });


   }
}

And your Adapter Class should be like below:

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);
    }
}



回答2:


if I were you I would try something like this:

its not a perfect solution just an idea of how you can do it, you would need to further modify it.

Create number of fagments = total number of categeries and name them like fragment0, fragment1 so on to the total number of categeries.

and then get the number of categeries first lets say

int count = number of categeries;

and then add fragments to ViewPager like this

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

and to name the fragments i.e tab title you can make list of fragment titles, something like this

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);
        }
    }

I hope it helps




回答3:


For Kotlin

After you get categoriy size, you can add dynamic tabs as per your categories size as below:

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?) {

            }
        })

    }
}

And here is your adapter 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)
    }
}


来源:https://stackoverflow.com/questions/38091002/how-can-i-create-dynamically-tab-with-viewpager-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!