How can i create dynamically tab with viewpager in android?

前端 未结 4 1186
别那么骄傲
别那么骄傲 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

    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);
        }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-02 15:27

    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)
        }
    }
    
    0 讨论(0)
  • 2021-02-02 15:32

    if you want to dynamic tablayout and viewpager you can use this below code for a kotlin;

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

    This area if you want non scrollable you can handle use it;

        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
    
    0 讨论(0)
提交回复
热议问题