How to use tablayout with bottom navigation and viewpager?

后端 未结 2 865
刺人心
刺人心 2021-01-19 17:49

I created an activity with a bottom navigation bar. I want tablayout when I want to switch to another fragment. And tablayout can con

2条回答
  •  一整个雨季
    2021-01-19 18:26

    You need to put view pager on Activity. Make a view pager Adapter. Connect your different fragment in your Adapter. After that you can set your Adapter on your Activity example is given below. O sorry we need to put your tab layout before vewPager. Connect your tab layout on your View Pager Adapter.

    activity_main.xml

    
    
       
    
    

    MainActivity.java

    public class MainActivity extends Activity {
       ViewPager viewpager;
       TabLayout tabLayout;
       public void onCreate(Bundle savedInstanceState) {
       viewpager = findViewById(R.id.viewpager);
       tabLayout = findViewById(R.id.tablayout);
       super.onCreate(saveedInstanceState);
       .........
       ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
       viewpager.setViewPager(adapter);
       tabLayout.setupWithViewPager(viewPager);     
       }
    }
    

    ViewPagerAdapter

    public class ViewPagerAdapter extends FragmentPagerAdapter {
     private String tabTitles [] = new String[] {"title first", "title Second"};
      public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    
    }
    
    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new YourFragmentFirst();
        } else if (....){
            return new YourFragmentSeconde();
        }
        ........  
    }
    
    @Override
    public int getCount() {
        return  //return your number of Fragment;
    }
    
    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }
    }
    

提交回复
热议问题