1. 程式人生 > >Android 底部導航欄(底部Tab)最佳實踐

Android 底部導航欄(底部Tab)最佳實踐

 

本文目錄.png

當開始一個新專案的時候,有一個很重要的步驟就是確定我們的APP首頁框架,也就是使用者從桌面點選APP 圖示,進入APP 首頁的時候展示給使用者的框架,比如微信,展示了有四個Tab,分別對應不同的板塊(微信、通訊錄、發現、我),現在市面出了少部分的Material Design 風格的除外,大部分都是這樣的一個框架,稱之為底部導航欄,分為3-5個Tab不等。前段時間開始了一個新專案,在搭建這樣一個Tab 框架的時候遇到了一些坑,前後換了好幾種方式來實現。因此,本文總結了通常實現這樣一個底部導航欄的幾種方式,以及它各自一些需要注意的地方。本文以實現如下一個底部導航欄為例:

本文實現示例.png

1 . TabLayout + Fragment

要實現這樣一個底部導航欄,大家最容易想到的當然就是TabLayout,Tab 切換嘛,TabLayout 就是專門幹這個事的,不過TabLayout 預設是帶有Indicator的,我們是不需要的,因此需要把它去掉,看一下佈局檔案:

 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. xmlns:app="http://schemas.android.com/apk/res-auto"

  4. android:orientation="vertical"

  5. android:layout_width="match_parent"

  6. android:layout_height="match_parent">

  7.  
  8. <FrameLayout

  9. android:id="@+id/home_container"

  10. android:layout_width="match_parent"

  11. android:layout_height="0dp"

  12. android:layout_weight="1"

  13. >

  14. </FrameLayout>

  15.  
  16. <View android:layout_width="match_parent"

  17. android:layout_height="0.5dp"

  18. android:alpha="0.6"

  19. android:background="@android:color/darker_gray"

  20. />

  21. <android.support.design.widget.TabLayout

  22. android:id="@+id/bottom_tab_layout"

  23. android:layout_width="match_parent"

  24. app:tabIndicatorHeight="0dp"

  25. app:tabSelectedTextColor="@android:color/black"

  26. app:tabTextColor="@android:color/darker_gray"

  27. android:layout_height="50dp">

  28.  
  29. </android.support.design.widget.TabLayout>

  30.  
  31. </LinearLayout>

整個佈局分為三個部分,最上面是一個Framelayout 用做裝Fragment 的容器,接著有一根分割線,最下面就是我們的TabLayout,去掉預設的Indicator直接設定app:tabIndicatorHeight屬性的值為0就行了。

佈局檔案寫好之後,接下來看一下Activity的程式碼:

 
  1. public class BottomTabLayoutActivity extends AppCompatActivity {

  2. private TabLayout mTabLayout;

  3. private Fragment []mFragmensts;

  4. @Override

  5. protected void onCreate(@Nullable Bundle savedInstanceState) {

  6. super.onCreate(savedInstanceState);

  7. setContentView(R.layout.bottom_tab_layout_ac);

  8. mFragmensts = DataGenerator.getFragments("TabLayout Tab");

  9.  
  10. initView();

  11.  
  12. }

  13.  
  14. private void initView() {

  15. mTabLayout = (TabLayout) findViewById(R.id.bottom_tab_layout);

  16.  
  17. mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

  18. @Override

  19. public void onTabSelected(TabLayout.Tab tab) {

  20. onTabItemSelected(tab.getPosition());

  21.  
  22. //改變Tab 狀態

  23. for(int i=0;i< mTabLayout.getTabCount();i++){

  24. if(i == tab.getPosition()){

  25. mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabResPressed[i]));

  26. }else{

  27. mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabRes[i]));

  28. }

  29. }

  30.  
  31. }

  32.  
  33. @Override

  34. public void onTabUnselected(TabLayout.Tab tab) {

  35.  
  36. }

  37.  
  38. @Override

  39. public void onTabReselected(TabLayout.Tab tab) {

  40.  
  41. }

  42. });

  43.  
  44. mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_home_selector)).setText(DataGenerator.mTabTitle[0]));

  45. mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_discovery_selector)).setText(DataGenerator.mTabTitle[1]));

  46. mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_attention_selector)).setText(DataGenerator.mTabTitle[2]));

  47. mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_profile_selector)).setText(DataGenerator.mTabTitle[3]));

  48.  
  49. }

  50.  
  51. private void onTabItemSelected(int position){

  52. Fragment fragment = null;

  53. switch (position){

  54. case 0:

  55. fragment = mFragmensts[0];

  56. break;

  57. case 1:

  58. fragment = mFragmensts[1];

  59. break;

  60.  
  61. case 2:

  62. fragment = mFragmensts[2];

  63. break;

  64. case 3:

  65. fragment = mFragmensts[3];

  66. break;

  67. }

  68. if(fragment!=null) {

  69. getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();

  70. }

  71. }

  72. }

Activity的程式碼如上,很簡單,就是一個TabLayout,新增監聽器,然後向TabLayout中新增4個Tab,在addOnTabSelectedListener 中切換各個Tab對應的Fragment 。其中用到的一些資料放在了一個單獨的類中, DataGenerator,程式碼如下:

 
  1. public class DataGenerator {

  2.  
  3. public static final int []mTabRes = new int[]{R.drawable.tab_home_selector,R.drawable.tab_discovery_selector,R.drawable.tab_attention_selector,R.drawable.tab_profile_selector};

  4. public static final int []mTabResPressed = new int[]{R.drawable.ic_tab_strip_icon_feed_selected,R.drawable.ic_tab_strip_icon_category_selected,R.drawable.ic_tab_strip_icon_pgc_selected,R.drawable.ic_tab_strip_icon_profile_selected};

  5. public static final String []mTabTitle = new String[]{"首頁","發現","關注","我的"};

  6.  
  7. public static Fragment[] getFragments(String from){

  8. Fragment fragments[] = new Fragment[4];

  9. fragments[0] = HomeFragment.newInstance(from);

  10. fragments[1] = DiscoveryFragment.newInstance(from);

  11. fragments[2] = AttentionFragment.newInstance(from);

  12. fragments[3] = ProfileFragment.newInstance(from);

  13. return fragments;

  14. }

  15.  
  16. /**

  17. * 獲取Tab 顯示的內容

  18. * @param context

  19. * @param position

  20. * @return

  21. */

  22. public static View getTabView(Context context,int position){

  23. View view = LayoutInflater.from(context).inflate(R.layout.home_tab_content,null);

  24. ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_content_image);

  25. tabIcon.setImageResource(DataGenerator.mTabRes[position]);

  26. TextView tabText = (TextView) view.findViewById(R.id.tab_content_text);

  27. tabText.setText(mTabTitle[position]);

  28. return view;

  29. }

  30. }

接下來,我們看一下效果:

Layout常規實現效果.png

執行之後,效果如上圖,What ? 圖示這麼小?圖示和文字之間的間距這麼寬?這當然不是我們想要的,試著用TabLayout的屬性調整呢?TabLayout 提供了設定Tab 圖示、tab 文字顏色,選中顏色,文字大小的屬性,但是很遺憾,圖示Icon和圖示與文字之間的間距是沒辦法調整的。

那麼就沒有辦法了嗎?在仔細查了一下TabLayout的API 後,找到了一個方法,Tab 中有一個setCustomView(View view)方法,也就是我們不用常規的方式建立Tab,我們可以提供一個自己定義的View 來建立Tab,這不就行了嘛,既然可以自定義,那麼icon的大小,icon和文字之間的間距,我們想怎樣就怎樣拉。於是我們自定義一個佈局:

 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:orientation="vertical"

  4. android:gravity="center"

  5. android:layout_width="match_parent"

  6. android:layout_height="match_parent">

  7. <ImageView

  8. android:id="@+id/tab_content_image"

  9. android:layout_width="wrap_content"

  10. android:layout_height="wrap_content"

  11. android:scaleType="centerCrop"

  12. />

  13. <TextView

  14. android:id="@+id/tab_content_text"

  15. android:layout_width="wrap_content"

  16. android:layout_height="wrap_content"

  17. android:textSize="10sp"

  18. android:textColor="@android:color/darker_gray"

  19. />

  20. </LinearLayout>

新增tab 的時候,用這個自定義的佈局,改造後的Activity中的程式碼如下這樣:

 
  1. public class BottomTabLayoutActivity extends AppCompatActivity {

  2. private TabLayout mTabLayout;

  3. private Fragment []mFragmensts;

  4. @Override

  5. protected void onCreate(@Nullable Bundle savedInstanceState) {

  6. super.onCreate(savedInstanceState);

  7. setContentView(R.layout.bottom_tab_layout_ac);

  8. mFragmensts = DataGenerator.getFragments("TabLayout Tab");

  9.  
  10. initView();

  11.  
  12. }

  13.  
  14. private void initView() {

  15. mTabLayout = (TabLayout) findViewById(R.id.bottom_tab_layout);

  16.  
  17. mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

  18. @Override

  19. public void onTabSelected(TabLayout.Tab tab) {

  20. onTabItemSelected(tab.getPosition());

  21. // Tab 選中之後,改變各個Tab的狀態

  22. for (int i=0;i<mTabLayout.getTabCount();i++){

  23. View view = mTabLayout.getTabAt(i).getCustomView();

  24. ImageView icon = (ImageView) view.findViewById(R.id.tab_content_image);

  25. TextView text = (TextView) view.findViewById(R.id.tab_content_text);

  26. if(i == tab.getPosition()){ // 選中狀態

  27. icon.setImageResource(DataGenerator.mTabResPressed[i]);

  28. text.setTextColor(getResources().getColor(android.R.color.black));

  29. }else{// 未選中狀態

  30. icon.setImageResource(DataGenerator.mTabRes[i]);

  31. text.setTextColor(getResources().getColor(android.R.color.darker_gray));

  32. }

  33. }

  34.  
  35.  
  36. }

  37.  
  38. @Override

  39. public void onTabUnselected(TabLayout.Tab tab) {

  40.  
  41. }

  42.  
  43. @Override

  44. public void onTabReselected(TabLayout.Tab tab) {

  45.  
  46. }

  47. });

  48. // 提供自定義的佈局新增Tab

  49. for(int i=0;i<4;i++){

  50. mTabLayout.addTab(mTabLayout.newTab().setCustomView(DataGenerator.getTabView(this,i)));

  51. }

  52.  
  53. }

  54.  
  55. private void onTabItemSelected(int position){

  56. Fragment fragment = null;

  57. switch (position){

  58. case 0:

  59. fragment = mFragmensts[0];

  60. break;

  61. case 1:

  62. fragment = mFragmensts[1];

  63. break;

  64.  
  65. case 2:

  66. fragment = mFragmensts[2];

  67. break;

  68. case 3:

  69. fragment = mFragmensts[3];

  70. break;

  71. }

  72. if(fragment!=null) {

  73. getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();

  74. }

  75. }

  76. }

改造完成之後,效果如下:

TabLayout自定義Tab佈局後的效果.gif

總結:TayoutLayout 實現底部導航欄較為簡單,只需幾步就能實現,能配合Viewpager使用。但是,就像上文說的,不能設定Icon大小和調整Icon和文字之間的間距。但是可以通過設定自定義佈局的方式來實現我們想要的效果。需要我們自己來改變Tab切換的狀態。還有一點需要注意:設定OnTabChangeListener 需要在新增Tab之前,不然第一次不會回撥onTabSelected()方法,前面寫過一片文章,從原始碼的角度分析這個坑,請看 TabLayout 踩坑之 onTabSelected沒有被回撥的問題

2 . BottomNavigationView + Fragment

除了用上面的TabLayout來實現底部導航欄,Google 也釋出了專門用來實現底部導航的控制元件,那就是BottomNavigationView,BottomNavigationView符合Material 風格,有著炫酷的切換動畫,我們來具體看一下。

佈局和前面TabLayout 實現的佈局長得差不多,把TabLayout換成 NavigationView 就行。這裡就不貼布局檔案了。BottomNavigationView 的Tab是通過menu 的方式新增的,看一下menu檔案:

 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <menu xmlns:android="http://schemas.android.com/apk/res/android">

  3. <item

  4. android:id="@+id/tab_menu_home"

  5. android:icon="@drawable/ic_play_circle_outline_black_24dp"

  6. android:title="首頁"

  7. />

  8. <item

  9. android:id="@+id/tab_menu_discovery"

  10. android:icon="@drawable/ic_favorite_border_black_24dp"

  11. android:title="發現"

  12. />

  13. <item

  14. android:id="@+id/tab_menu_attention"

  15. android:icon="@drawable/ic_insert_photo_black_24dp"

  16. android:title="關注"

  17. />

  18. <item

  19. android:id="@+id/tab_menu_profile"

  20. android:icon="@drawable/ic_clear_all_black_24dp"

  21. android:title="我的"

  22. />

  23.  
  24. </menu>

Activity 程式碼如下:

 
  1. public class BottomNavigationViewActivity extends AppCompatActivity {

  2. private BottomNavigationView mBottomNavigationView;

  3. private Fragment []mFragments;

  4. @Override

  5. protected void onCreate(@Nullable Bundle savedInstanceState) {

  6. super.onCreate(savedInstanceState);

  7. setContentView(R.layout.bottom_navigation_view_ac);

  8.  
  9. mFragments = DataGenerator.getFragments("BottomNavigationView Tab");

  10.  
  11. initView();

  12. }

  13.  
  14. private void initView() {

  15. mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation_view);

  16. //mBottomNavigationView.getMaxItemCount()

  17.  
  18. mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

  19. @Override

  20. public boolean onNavigationItemSelected(@NonNull MenuItem item) {

  21. onTabItemSelected(item.getItemId());

  22. return true;

  23. }

  24. });

  25.  
  26. // 由於第一次進來沒有回撥onNavigationItemSelected,因此需要手動呼叫一下切換狀態的方法

  27. onTabItemSelected(R.id.tab_menu_home);

  28. }

  29.  
  30. private void onTabItemSelected(int id){

  31. Fragment fragment = null;

  32. switch (id){

  33. case R.id.tab_menu_home:

  34. fragment = mFragments[0];

  35. break;

  36. case R.id.tab_menu_discovery:

  37. fragment = mFragments[1];

  38. break;

  39.  
  40. case R.id.tab_menu_attention:

  41. fragment = mFragments[2];

  42. break;

  43. case R.id.tab_menu_profile:

  44. fragment = mFragments[3];

  45. break;

  46. }

  47. if(fragment!=null) {

  48. getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();

  49. }

  50. }

  51. }

程式碼比TabLayout 還簡單,不用新增tab ,直接在xml 檔案中設定menu屬性就好了。效果如下:

bottom_navigaiton_view 效果.gif

效果如上,切換的時候會有動畫,效果還是不錯的,除此之外,每個tab還可以對應不同的背景色,有興趣的可以去試一下。但是有一點值得吐槽,動畫好像還不能禁止,要是設計成可以禁止動畫和使用切換動畫這兩種模式,隨意切換就好了。

總結:BottomNavigationView 實現底部導航欄符合Material風格,有炫酷的切換動畫,且動畫還不能禁止,如果App 需要這種風格的底部導航欄的,可以用這個,實現起來比較簡單。但是需要注意:BottomNavigatonView 的tab 只能是3-5個,多了或者少了是會報錯。還有一點,第一次進入頁面的時候不會呼叫onNavigationItemSelected 方法(不知道是不是 哪兒沒有設定對?如果有同學發現可以,評論區告訴我一下),因此第一次需要手動呼叫 新增fragment的方法。

3 . FragmentTabHost + Fragment

FragmentTab Host 可能是大家實現底部導航欄用得最多的一種方式,特別是在TabLayout 和 BottomNavigation 出來之前,是比較老牌的實現底部導航欄的方式,相比前兩個,FragmentTabHost 的實現稍微複雜一點,具體請看程式碼,

 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:orientation="vertical"

  4. android:layout_width="match_parent"

  5. android:layout_height="match_parent">

  6.  
  7. <FrameLayout

  8. android:id="@+id/home_container"

  9. android:layout_width="match_parent"

  10. android:layout_height="0dp"

  11. android:layout_weight="1"

  12. >

  13. </FrameLayout>

  14.  
  15. <View android:layout_width="match_parent"

  16. android:layout_height="0.5dp"

  17. android:alpha="0.6"

  18. android:background="@android:color/darker_gray"

  19. />

  20.  
  21. <android.support.v4.app.FragmentTabHost

  22. android:id="@android:id/tabhost"

  23. android:layout_width="match_parent"

  24. android:layout_marginTop="3dp"

  25. android:layout_height="50dp">

  26. <FrameLayout

  27. android:id="@android:id/tabcontent"

  28. android:layout_width="0dp"

  29. android:layout_height="0dp"

  30. >

  31.  
  32. </FrameLayout>

  33. </android.support.v4.app.FragmentTabHost>

  34. </LinearLayout>

佈局檔案需要注意的地方:1,FragmentTabHost 裡需要有一個id為@android:id/tabcontent的佈局。2,FragmentTabHost的id 也是系統提供的id ,不能隨便起。

Activity 程式碼如下:

 
  1. public class FragmentTabHostActivity extends AppCompatActivity implements TabHost.OnTabChangeListener{

  2. private Fragment []mFragments;

  3. private FragmentTabHost mTabHost;

  4. @Override

  5. protected void onCreate(@Nullable Bundle savedInstanceState) {

  6. super.onCreate(savedInstanceState);

  7. setContentView(R.layout.fragment_tab_host_ac_layout);

  8. mFragments = DataGenerator.getFragments("FragmentTabHost Tab");

  9. initView();

  10.  
  11. }

  12.  
  13. private void initView(){

  14. mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

  15.  
  16. // 關聯TabHost

  17. mTabHost.setup(this,getSupportFragmentManager(),R.id.home_container);

  18. //注意,監聽要設定在新增Tab之前

  19. mTabHost.setOnTabChangedListener(this);

  20.  
  21.  
  22. //新增Tab

  23. for (int i=0;i<4;i++){

  24. //生成TabSpec

  25. TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTabTitle[i]).setIndicator(DataGenerator.getTabView(this,i));

  26. // 新增Tab 到TabHost,並繫結Fragment

  27. Bundle bundle = new Bundle();

  28. bundle.putString("from","FragmentTabHost Tab");

  29. mTabHost.addTab(tabSpec,mFragments[i].getClass(),bundle);

  30. }

  31.  
  32.  
  33. //去掉Tab 之間的分割線

  34. mTabHost.getTabWidget().setDividerDrawable(null);

  35. //

  36. mTabHost.setCurrentTab(0);

  37. }

  38.  
  39.  
  40.  
  41. @Override

  42. public void onTabChanged(String tabId) {

  43. updateTabState();

  44.  
  45. }

  46.  
  47. /**

  48. * 更新Tab 的狀態

  49. */

  50. private void updateTabState(){

  51. TabWidget tabWidget = mTabHost.getTabWidget();

  52. for (int i=0;i<tabWidget.getTabCount();i++){

  53. View view = tabWidget.getChildTabViewAt(i);

  54. ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_content_image);

  55. TextView tabText = (TextView) view.findViewById(R.id.tab_content_text);

  56. if(i == mTabHost.getCurrentTab()){

  57. tabIcon.setImageResource(DataGenerator.mTabResPressed[i]);

  58. tabText.setTextColor(getResources().getColor(android.R.color.black));

  59. }else{

  60. tabIcon.setImageResource(mTabRes[i]);

  61. tabText.setTextColor(getResources().getColor(android.R.color.darker_gray));

  62. }

  63. }

  64. }

  65. }

FragmentTabHost 的實現就比前兩個稍微複雜點。首先要通過setup()方法建立FragmentTabHost 與Fragment container的關聯。然後設定Tab切換監聽,新增Tab。需要主要一點,FragmentTabHost 預設在每個Tab之間有一跟豎直的分割先,呼叫下面這行程式碼去掉分割線:

 
  1. //去掉Tab 之間的分割線

  2. mTabHost.getTabWidget().setDividerDrawable(null);

onTabChanged 回撥中需要手動設定每個Tab切換的狀態。從
TabWidget 中取出每個子View 來設定選中和未選中的狀態(跟前面的TabLayout 通過自定義佈局新增Tab是一樣的)。

效果如下:

FragmentTabHost.gif

注意:有2點需要注意,1,通過FragmentTabHost新增的Fragment 裡面收不到通過 setArgment() 傳遞的引數,要傳遞引數,需要在新增Tab 的時候通過Bundle 來傳參,程式碼如下:

 
  1. // 新增Tab 到TabHost,並繫結Fragment

  2. Bundle bundle = new Bundle();

  3. bundle.putString("from","FragmentTabHost Tab");

2,同前面說的TabLayout一樣,要在新增Tab之前設定OnTabChangeListener 監聽器,否則第一次收不到onTabChange回撥。

總結:FragmentTabHost 實現底部導航欄比前面兩種方式稍微複雜一點,需要注意的地方有點多,不然容易踩坑,但是它的穩定性和相容性很好,在Android 4.x 時代就大量使用了。能配合Viewpager使用。

4 . RadioGroup + RadioButton + Fragment

RadioGroup +RadioButtom 是做單選的,RadioGroup 裡面的View 只能選中一個。想一下我們要做的底部導航欄,是不是就是一個單選模式呢?當然是,每次只能選中一個頁面嘛,因此用RadioGroup + RadioButton 來實現底部導航欄也是一種方式。

RadioButton 有預設的選中與非選中的樣式,預設顏色是colorAcent,效果是這樣的:

RadioGroup效果.png

因此我們要用RadioGroup+RadioButton 實現底部導航欄,首先,就是去掉它的預設樣式,因此,我們來自定義一個style:

 
  1. <style name="RadioGroupButtonStyle" >

  2. <!-- 這個屬性是去掉button 預設樣式-->

  3. <item name="android:button">@null</item>

  4.  
  5. <item name="android:gravity">center</item>

  6. <item name="android:layout_width">0dp</item>

  7. <item name="android:layout_height">wrap_content</item>

  8. <item name="android:layout_weight">1</item>

  9. <item name="android:textSize">12sp</item>

  10. <item name="android:textColor">@color/color_selector</item>

  11. </style>

style 裡面定義了RadioButton 的屬性,現在我們直接給RadioButton 設定style 就好了,看先頁面的佈局檔案:

 
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:orientation="vertical"

  4. android:layout_width="match_parent"

  5. android:layout_height="match_parent">

  6.  
  7. <FrameLayout

  8. android:id="@+id/home_container"

  9. android:layout_width="match_parent"

  10. android:layout_height="0dp"

  11. android:layout_weight="1"

  12. >

  13. </FrameLayout>

  14.  
  15. <View android:layout_width="match_parent"

  16. android:layout_height="0.5dp"

  17. android:alpha="0.6"

  18. android:background="@android:color/darker_gray"

  19. />

  20. <RadioGroup

  21. android:id="@+id/radio_group_button"

  22. android:layout_width="match_parent"

  23. android:layout_height="50dp"

  24. android:orientation="horizontal"

  25. android:gravity="center"

  26. android:background="@android:color/white"

  27. >

  28. <RadioButton

  29. android:id="@+id/radio_button_home"

  30. android:layout_width="wrap_content"

  31. android:layout_height="wrap_content"

  32. android:text="首頁"

  33. android:drawableTop="@drawable/tab_home_selector"

  34. style="@style/RadioGroupButtonStyle"

  35. />

  36. <RadioButton

  37. android:id="@+id/radio_button_discovery"

  38. android:layout_width="wrap_content"

  39. android:layout_height="wrap_content"

  40. android:text="發現"

  41. android:drawableTop="@drawable/tab_discovery_selector"

  42. style="@style/RadioGroupButtonStyle"

  43. />

  44. <RadioButton

  45. android:id="@+id/radio_button_attention"

  46. android:layout_width="wrap_content"

  47. android:layout_height="wrap_content"

  48. android:text="關注"

  49. android:drawableTop="@drawable/tab_attention_selector"

  50. style="@style/RadioGroupButtonStyle"

  51. />

  52. <RadioButton

  53. android:id="@+id/radio_button_profile"

  54. android:layout_width="wrap_content"

  55. android:layout_height="wrap_content"

  56. android:text="我的"

  57. android:drawableTop="@drawable/tab_profile_selector"

  58. style="@style/RadioGroupButtonStyle"

  59. />

  60. </RadioGroup>

  61. </LinearLayout>

很簡單,新增一個RadioGroup 和 四個 RadioButton ,因為去掉了原來的樣式,因此要設定我們每個RadioButton 顯示的圖示。

佈局檔案定義好了之後,看一下Activity 中的程式碼:

 
  1. public class RadioGroupTabActivity extends AppCompatActivity {

  2. private RadioGroup mRadioGroup;

  3. private Fragment []mFragments;

  4. private RadioButton mRadioButtonHome;

  5. @Override

  6. protected void onCreate(@Nullable Bundle savedInstanceState) {

  7. super.onCreate(savedInstanceState);

  8. setContentView(R.layout.radiogroup_tab_layout);

  9. mFragments = DataGenerator.getFragments("RadioGroup Tab");

  10. initView();

  11. }

  12.  
  13. private void initView() {

  14. mRadioGroup = (RadioGroup) findViewById(R.id.radio_group_button);

  15. mRadioButtonHome = (RadioButton) findViewById(R.id.radio_button_home);

  16. mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

  17. Fragment mFragment = null;

  18. @Override

  19. public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

  20. switch (checkedId){

  21. case R.id.radio_button_home:

  22. mFragment = mFragments[0];

  23. break;

  24. case R.id.radio_button_discovery:

  25. mFragment = mFragments[1];

  26. break;

  27. case R.id.radio_button_attention:

  28. mFragment = mFragments[2];

  29. break;

  30. case R.id.radio_button_profile:

  31. mFragment = mFragments[3];

  32. break;

  33. }

  34. if(mFragments!=null){

  35. getSupportFragmentManager().beginTransaction().replace(R.id.home_container,mFragment).commit();

  36. }

  37. }

  38. });

  39. // 保證第一次會回撥OnCheckedChangeListener

  40. mRadioButtonHome.setChecked(true);

  41. }

  42. }

Activity 的程式碼就很簡單了,在onCheckedChanged 回撥裡面切換Fragment 就行了。這種方式的Activity 程式碼是最簡潔的,因為RadioButton 有check 和 unCheck 狀態,直接用seletor 就能換狀態的圖示和check 文字的顏色,不用手動來設定狀態。

效果如下,一步到位:

RadioGroup 實現底部Tab效果

總結:RadioGroup + RadioButton 實現底部導航欄步驟有點多,需要配置style 檔案,各個Tab 的 drawable selector 檔案,color 檔案,但是,配置完了這些之後,程式碼是最簡潔的。這也是有好處的,以後要換什麼圖示啊,顏色,只需要改xml 檔案就好,是不需要改程式碼邏輯的,因此這樣方式來實現底部導航欄是個不錯的選擇。

5 . 自定義 CustomTabView + Fragment

除了上面的幾種方式之外,還有一種方式來實現底部導航欄,那就是我們通過自定義View來實現,自定義View的好處是我們可以按照我們想要的高度定製,缺點是:比起這些現有的控制元件還是有點麻煩。下面就通過自定義一個CustomTabView 為例子,來實現一個底部導航欄。

CustomTabView 程式碼下:

 
  1. public class CustomTabView extends LinearLayout implements View.OnClickListener{

  2. private List<View> mTabViews;//儲存TabView

  3. private List<Tab> mTabs;// 儲存Tab

  4. private OnTabCheckListener mOnTabCheckListener;

  5.  
  6. public void setOnTabCheckListener(OnTabCheckListener onTabCheckListener) {

  7. mOnTabCheckListener = onTabCheckListener;

  8. }

  9.  
  10. public CustomTabView(Context context) {

  11. super(context);

  12. init();

  13. }

  14.  
  15. public CustomTabView(Context context, @Nullable AttributeSet attrs) {

  16. super(context, attrs);

  17. init();

  18. }

  19.  
  20. public CustomTabView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

  21. super(context, attrs, defStyleAttr);

  22. init();

  23. }

  24.  
  25. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

  26. public CustomTabView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {

  27. super(context, attrs, defStyleAttr, defStyleRes);

  28. init();

  29. }

  30.  
  31. private void init(){

  32. setOrientation(HORIZONTAL);

  33. setGravity(Gravity.CENTER);

  34. mTabViews = new ArrayList<>();

  35. mTabs = new ArrayList<>();

  36.  
  37. }

  38.  
  39. /**

  40. * 新增Tab

  41. * @param tab

  42. */

  43. public void addTab(Tab tab){

  44. View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab_item_layout,null);

  45. TextView textView = (TextView) view.findViewById(R.id.custom_tab_text);

  46. ImageView imageView = (ImageView) view.findViewById(R.id.custom_tab_icon);

  47. imageView.setImageResource(tab.mIconNormalResId);

  48. textView.setText(tab.mText);

  49. textView.setTextColor(tab.mNormalColor);

  50.  
  51. view.setTag(mTabViews.size());

  52. view.setOnClickListener(this);

  53.  
  54. mTabViews.add(view);

  55. mTabs.add(tab);

  56.  
  57. addView(view);

  58.  
  59. }

  60.  
  61. /**

  62. * 設定選中Tab

  63. * @param position

  64. */

  65. public void setCurrentItem(int position){

  66. if(position>=mTabs.size() || position<0){

  67. position = 0;

  68. }

  69.  
  70. mTabViews.get(position).performClick();

  71.  
  72. updateState(position);

  73.  
  74.  
  75. }

  76.  
  77. /**

  78. * 更新狀態

  79. * @param position

  80. */

  81. private void updateState(int position){

  82. for(int i= 0;i<mTabViews.size();i++){

  83. View view = mTabViews.get(i);

  84. TextView textView = (TextView) view.findViewById(R.id.custom_tab_text);

  85. ImageView imageView = (ImageView) view.findViewById(R.id.custom_tab_icon);

  86. if(i == position){

  87. imageView.setImageResource(mTabs.get(i).mIconPressedResId);

  88. textView.setTextColor(mTabs.get(i).mSelectColor);

  89. }else{

  90. imageView.setImageResource(mTabs.get(i).mIconNormalResId);

  91. textView.setTextColor(mTabs.get(i).mNormalColor);

  92. }

  93. }

  94. }

  95.  
  96.  
  97. @Override

  98. public void onClick(View v) {

  99. int position = (int) v.getTag();

  100. if(mOnTabCheckListener!=null){

  101. mOnTabCheckListener.onTabSelected(v, position);

  102. }

  103.  
  104. updateState(position);

  105. }

  106.  
  107. public interface OnTabCheckListener{

  108. public void onTabSelected(View v,int position);

  109. }

  110.  
  111.  
  112. public static class Tab{

  113. private int mIconNormalResId;

  114. private int mIconPressedResId;

  115. private int mNormalColor;

  116. private int mSelectColor;

  117. private String mText;

  118.  
  119.  
  120. public Tab setText(String text){

  121. mText = text;

  122. return this;

  123. }

  124.  
  125. public Tab setNormalIcon(int res){

  126. mIconNormalResId = res;

  127. return this;

  128. }

  129.  
  130. public Tab setPressedIcon(int res){

  131. mIconPressedResId = res;

  132. return this;

  133. }

  134.  
  135. public Tab setColor(int color){

  136. mNormalColor = color;

  137. return this;

  138. }

  139.  
  140. public Tab setCheckedColor(int color){

  141. mSelectColor = color;

  142. return this;

  143. }

  144. }

  145.  
  146. @Override

  147. protected void onDetachedFromWindow() {

  148. super.onDetachedFromWindow();

  149. if(mTabViews!=null){

  150. mTabViews.clear();

  151. }

  152. if(mTabs!=null){

  153. mTabs.clear();

  154. }

  155. }

  156.  
  157. @Override

  158. protected void onAttachedToWindow() {

  159. super.onAttachedToWindow();

  160. // 調整每個Tab的大小

  161. for(int i=0;i<mTabViews.size();i++){

  162. View view = mTabViews.get(i);

  163. int width = getResources().getDisplayMetrics().widthPixels / (mTabs.size());

  164. LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);

  165.  
  166. view.setLayoutParams(params);

  167. }

  168.  
  169. }

  170. }

還是比較簡單,繼承LinearLayout,有一個Tab 類來儲存每個tab 的資料,比如圖示,顏色,文字等等,有註釋,就不一一解釋了。

佈局檔案差不多,其他控制元件換成CustomTabView 就行,看一下Activity中的程式碼:

 
  1. public class CustomTabActivity extends AppCompatActivity implements CustomTabView.OnTabCheckListener{

  2. private CustomTabView mCustomTabView;

  3. private Fragment []mFragmensts;

  4. @Override

  5. protected void onCreate(@Nullable Bundle savedInstanceState) {

  6. super.onCreate(savedInstanceState);

  7. setContentView(R.layout.custom_tab_ac_layout);

  8. mFragmensts = DataGenerator.getFragments("CustomTabView Tab");

  9. initView();

  10.  
  11. }

  12.  
  13. private void initView() {

  14. mCustomTabView = (CustomTabView) findViewById(R.id.custom_tab_container);

  15. CustomTabView.Tab tabHome = new CustomTabView.Tab().setText("首頁")

  16. .setColor(getResources().getColor(android.R.color.darker_gray))

  17. .setCheckedColor(getResources().getColor(android.R.color.black))

  18. .setNormalIcon(R.drawable.ic_tab_strip_icon_feed)

  19. .setPressedIcon(R.drawable.ic_tab_strip_icon_feed_selected);

  20. mCustomTabView.addTab(tabHome);

  21. CustomTabView.Tab tabDis = new CustomTabView.Tab().setText("發現")

  22. .setColor(getResources().getColor(android.R.color.darker_gray))

  23. .setCheckedColor(getResources().getColor(android.R.color.black))

  24. .setNormalIcon(R.drawable.ic_tab_strip_icon_category)

  25. .setPressedIcon(R.drawable.ic_tab_strip_icon_category_selected);

  26. mCustomTabView.addTab(tabDis);

  27. CustomTabView.Tab tabAttention = new CustomTabView.Tab().setText("管制")

  28. .setColor(getResources().getColor(android.R.color.darker_gray))

  29. .setCheckedColor(getResources().getColor(android.R.color.black))

  30. .setNormalIcon(R.drawable.ic_tab_strip_icon_pgc)

  31. .setPressedIcon(R.drawable.ic_tab_strip_icon_pgc_selected);

  32. mCustomTabView.addTab(tabAttention);

  33. CustomTabView.Tab tabProfile = new CustomTabView.Tab().setText("我的")

  34. .setColor(getResources().getColor(android.R.color.darker_gray))

  35. .setCheckedColor(getResources().getColor(android.R.color.black))

  36. .setNormalIcon(R.drawable.ic_tab_strip_icon_profile)

  37. .setPressedIcon(R.drawable.ic_tab_strip_icon_profile_selected);

  38. mCustomTabView.addTab(tabProfile);

  39. //設定監聽

  40. mCustomTabView.setOnTabCheckListener(this);

  41. // 預設選中tab

  42. mCustomTabView.setCurrentItem(0);

  43.  
  44. }

  45.  
  46. @Override

  47. public void onTabSelected(View v, int position) {

  48. Log.e("zhouwei","position:"+position);

  49. onTabItemSelected(position);

  50. }

  51.  
  52. private void onTabItemSelected(int position){

  53. Fragment fragment = null;

  54. switch (position){

  55. case 0:

  56. fragment =