現在基本上大部分的手機APP都要實現底部Tab,底部實現Tab的實現方式有很多種,那么有沒有好的實現方式呢?
今天我將使用一個開源插件來實現底部Tab
參考自zhangli_的博客:http://blog.csdn.net/zhangli_/article/details/52604699
效果圖(大家如果有制作gif的好方法可以推薦給我)
實現步驟如下:
1.添加依賴
2.在布局文件中添加tab容器
3.初始化UI
4.添加tab控制代碼
1.添加依賴
compile ‘me.majiajie:pager-bottom-tab-strip:1.0.0’
2.在布局文件中添加tab容器
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainTestActivity"> <me.majiajie.pagerbottomtabstrip.PagerBottomTabLayout android:id="@+id/boom_layout" app:elevation="8dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"/> <FrameLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/boom_layout" /> </RelativeLayout>
3.初始化UI
private void initView() { mHomePageFragment = HomePageFragment.newInstance(); mMePageFragment = MePageFragment.newInstance(); fragments = new Fragment[]{mHomePageFragment, mMePageFragment}; // 將fragment添加到framlayout中,並顯示第一個fragment getSupportFragmentManager().beginTransaction() .add(R.id.main_content, mHomePageFragment, mHomePageFragment.getClass().getName()) .add(R.id.main_content, mMePageFragment, mMePageFragment.getClass().getName()).commit(); //初始化底部導航欄 PagerBottomTabLayout mBottomTabLayout = (PagerBottomTabLayout) findViewById(R.id.boom_layout); //構建導航欄,得到Controller進行后續控制 mTabController = mBottomTabLayout.builder() .addTabItem(R.drawable.ic_menu_home, "首頁", getResources().getColor(R.color.lightblue)) .addTabItem(R.drawable.ic_menu_me, "我", getResources().getColor(R.color.lightblue)) .setMode(TabLayoutMode.HIDE_TEXT | TabLayoutMode.CHANGE_BACKGROUND_COLOR) .setDefaultColor(getResources().getColor(R.color.black)) .build(); }
4.添加tab控制代碼
private void setOnClickListeners() { mTabController.addTabItemClickListener(new OnTabItemSelectListener() { @Override public void onSelected(int index, Object tag) { FragmentTransaction trx = getSupportFragmentManager().beginTransaction(); trx.hide(mHomePageFragment).hide(mMePageFragment); if (!fragments[index].isAdded()) { trx.add(R.id.main_content, fragments[index]); } trx.show(fragments[index]).commitAllowingStateLoss(); } @Override public void onRepeatClick(int index, Object tag) { } }); }
初始化UI和Tab控制的函數在Activity中調用就可以了
這樣我們就生成了我們的底部Tab導航欄啦!!!