有两种方法可以实现。
一:使用bottomNavigationView+viewPager+fragment
二:使用mBottomNavigationBar+viewPager+fragment
第一种在使用中如果内容的数目大于3,会有一些问题,所以使用第二种。
首先在app的build.gradle中添加依赖compile 'com.ashokvarma.android:bottom-navigation-bar:2.0.4',版本好不重要,重新sync。
在activity_main.xml中添加viewPager,设置layout_weight="1",添加com.ashokvarma.bottomnavigation.BottomNavigationBar组件,layout_gravity设置为bottom。
创建对应的frangment.xml以及对应java文件。然后创建FragAdapter类继承FragmentPagerAdapter,
重写getItem()和getCount()方法。Fragment的list添加对应的frangment类,通过FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments)添加frangment,通过viewPager.setAdapter(adapter)添加对应的adapter。代码如下:
//构造适配器 Listfragments=new ArrayList();
fragments.add(new FragmentClass());
fragments.add(new FragmentChouke());
fragments.add(new FragmentQA());
fragments.add(new FragmentMy());
FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
接下来是mBottomNavigationBar的使用的相关代码(MODE_FIXED和BACKGROUND_STYLE_STATIC)解决了bottomNavigationView的内容大于3时的问题:
mBottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar_container);
mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
mBottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
mBottomNavigationBar.addItem(new BottomNavigationItem(R.drawable.unselector_tab_class, "课程").setActiveColorResource(R.color.colorPrimary))
.addItem(new BottomNavigationItem(R.drawable.unselector_tab_choubei, "筹课").setActiveColorResource(R.color.colorPrimary))
.addItem(new BottomNavigationItem(R.drawable.unselector_tab_qa, "答疑").setActiveColorResource(R.color.colorPrimary))
.addItem(new BottomNavigationItem(R.drawable.unselector_tab_me, "我的").setActiveColorResource(R.color.colorPrimary))//依次添加item,分别icon和名称
.setFirstSelectedPosition(0)//设置默认选择item
.initialise();//初始化
下面添加mBottomNavigationBar和viewPager的监听事件。
BottomNavigationBar监听事件
mBottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
@Override
public void onTabSelected(int position) {
viewPager.setCurrentItem(position);
Toast.makeText(MainActivity.this, "你好!", Toast.LENGTH_LONG).show();
textView.setText(toolbarText[position]);
}
@Override
public void onTabUnselected(int position) {
}
@Override
public void onTabReselected(int position) {
}
});
//pageView监听事件
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mBottomNavigationBar.selectTab(position);
textView.setText(toolbarText[position]);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});