-
在project下的build.grade中添加依赖 compile 'com.ashokvarma.android:bottom-navigation-bar:0.9.5' 2.在主布局文件中加入代码 <LinearLayout android:id="@+id/tb" android:layout_below="@id/title" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" />
<!--利用BottomNavigationBar来显示导航栏-->
<com.ashokvarma.bottomnavigation.BottomNavigationBar android:id="@+id/bottom_navigation_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"/> 3.在主Activity中的onCreate方法中添加如下逻辑 bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar); bottomNavigationBar .addItem(new BottomNavigationItem(R.mipmap.main_nav_home, "主页").setActiveColor(R.color.colorTheme)) .addItem(new BottomNavigationItem(R.mipmap.main_nav_water, "水").setActiveColor(R.color.colorTheme)) .addItem(new BottomNavigationItem(R.mipmap.main_nav_electric, "电").setActiveColor(R.color.colorTheme)) .addItem(new BottomNavigationItem(R.mipmap.main_nav_gas, "燃气").setActiveColor(R.color.colorTheme)) .addItem(new BottomNavigationItem(R.mipmap.main_nav_heat, "热力").setActiveColor(R.color.colorTheme)) .setFirstSelectedPosition(lastSelectedPosition) .initialise(); bottomNavigationBar.setTabSelectedListener(this); setDefaultFragment(); 4.在主Activity中添加如下方法 /**
- 设置默认的 */ private void setDefaultFragment() { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mHomeFragment = HomeFragment.newInstance(); transaction.replace(R.id.tb, mHomeFragment); transaction.commit(); }
@Override public void onTabSelected(int position) { Log.d(TAG, "onTabSelected() called with: " + "position = [" + position + "]"); FragmentManager fm = this.getFragmentManager(); //开启事务 FragmentTransaction transaction = fm.beginTransaction(); switch (position) { case 0: if (mHomeFragment == null) { mHomeFragment = HomeFragment.newInstance(); } transaction.replace(R.id.tb, mHomeFragment); break; case 1: if (mWaterFragment == null) { mWaterFragment = WaterFragment.newInstance(); } transaction.replace(R.id.tb, mWaterFragment); break; case 2: if (mElectricFragment == null) { mElectricFragment = ElectricFragment.newInstance(); } transaction.replace(R.id.tb, mElectricFragment); break; case 3: if (mGasFragment == null) { mGasFragment = GasFragment.newInstance(); } transaction.replace(R.id.tb, mGasFragment); break; case 4: if (mHeatFragment == null) { mHeatFragment = HeatFragment.newInstance(); } transaction.replace(R.id.tb, mHeatFragment); break; default: break; } // 事务提交 transaction.commit(); }
@Override public void onTabUnselected(int position) { Log.d(TAG, "onTabUnselected() called with: " + "position = [" + position + "]"); }
@Override public void onTabReselected(int position) {
} 5.创建几个Fragment(这里就不写了,随便创建都行)
转载于:https://my.oschina.net/u/2619068/blog/718852