How can i create dynamically tab with viewpager in android?

前端 未结 4 1195
别那么骄傲
别那么骄傲 2021-02-02 14:47

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

4条回答
  •  名媛妹妹
    2021-02-02 15:14

    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

提交回复
热议问题