How can i create dynamically tab with viewpager in android?

前端 未结 4 1185
别那么骄傲
别那么骄傲 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);
        }
    }
    

提交回复
热议问题