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


本文目錄.png

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


本文實現示例.png

1 . TabLayout + Fragment

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/home_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <View android:layout_width="match_parent"
          android:layout_height="0.5dp"
          android:alpha="0.6"
          android:background="@android:color/darker_gray"
        />
    <android.support.design.widget.TabLayout
        android:id="@+id/bottom_tab_layout"
        android:layout_width="match_parent"
        app:tabIndicatorHeight="0dp"
        app:tabSelectedTextColor="@android:color/black"
        app:tabTextColor="@android:color/darker_gray"
        android:layout_height="50dp">

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

</LinearLayout>

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

布局文件寫好之后,接下來看一下Activity的代碼:

public class BottomTabLayoutActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private Fragment []mFragmensts;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_tab_layout_ac);
        mFragmensts = DataGenerator.getFragments("TabLayout Tab");

        initView();

    }

    private void initView() {
        mTabLayout = (TabLayout) findViewById(R.id.bottom_tab_layout);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabItemSelected(tab.getPosition());

                //改變Tab 狀態
                for(int i=0;i< mTabLayout.getTabCount();i++){
                    if(i == tab.getPosition()){
                        mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabResPressed[i]));
                    }else{
                        mTabLayout.getTabAt(i).setIcon(getResources().getDrawable(DataGenerator.mTabRes[i]));
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_home_selector)).setText(DataGenerator.mTabTitle[0]));
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_discovery_selector)).setText(DataGenerator.mTabTitle[1]));
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_attention_selector)).setText(DataGenerator.mTabTitle[2]));
        mTabLayout.addTab(mTabLayout.newTab().setIcon(getResources().getDrawable(R.drawable.tab_profile_selector)).setText(DataGenerator.mTabTitle[3]));

    }

    private void onTabItemSelected(int position){
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = mFragmensts[0];
                break;
            case 1:
                fragment = mFragmensts[1];
                break;

            case 2:
                fragment = mFragmensts[2];
                break;
            case 3:
                fragment = mFragmensts[3];
                break;
        }
        if(fragment!=null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();
        }
    }
}

Activity的代碼如上,很簡單,就是一個TabLayout,添加監聽器,然后向TabLayout中添加4個Tab,在addOnTabSelectedListener 中切換各個Tab對應的Fragment 。其中用到的一些數據放在了一個單獨的類中, DataGenerator,代碼如下:

public class DataGenerator {

    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};
    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};
    public static final String []mTabTitle = new String[]{"首頁","發現","關注","我的"};

    public static Fragment[] getFragments(String from){
        Fragment fragments[] = new Fragment[4];
        fragments[0] = HomeFragment.newInstance(from);
        fragments[1] = DiscoveryFragment.newInstance(from);
        fragments[2] = AttentionFragment.newInstance(from);
        fragments[3] = ProfileFragment.newInstance(from);
        return fragments;
    }

    /**
     * 獲取Tab 顯示的內容
     * @param context
     * @param position
     * @return
     */
    public static View getTabView(Context context,int position){
        View view = LayoutInflater.from(context).inflate(R.layout.home_tab_content,null);
        ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_content_image);
        tabIcon.setImageResource(DataGenerator.mTabRes[position]);
        TextView tabText = (TextView) view.findViewById(R.id.tab_content_text);
        tabText.setText(mTabTitle[position]);
        return view;
    }
}

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


Layout常規實現效果.png

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:gravity="center"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ImageView
        android:id="@+id/tab_content_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        />
    <TextView
        android:id="@+id/tab_content_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:textColor="@android:color/darker_gray"
        />
</LinearLayout>

添加tab 的時候,用這個自定義的布局,改造后的Activity中的代碼如下這樣:

public class BottomTabLayoutActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private Fragment []mFragmensts;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_tab_layout_ac);
        mFragmensts = DataGenerator.getFragments("TabLayout Tab");

        initView();

    }

    private void initView() {
        mTabLayout = (TabLayout) findViewById(R.id.bottom_tab_layout);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabItemSelected(tab.getPosition());
                // Tab 選中之后,改變各個Tab的狀態
               for (int i=0;i<mTabLayout.getTabCount();i++){
                   View view = mTabLayout.getTabAt(i).getCustomView();
                   ImageView icon = (ImageView) view.findViewById(R.id.tab_content_image);
                   TextView text = (TextView) view.findViewById(R.id.tab_content_text);
                   if(i == tab.getPosition()){ // 選中狀態
                       icon.setImageResource(DataGenerator.mTabResPressed[i]);
                       text.setTextColor(getResources().getColor(android.R.color.black));
                   }else{// 未選中狀態
                       icon.setImageResource(DataGenerator.mTabRes[i]);
                       text.setTextColor(getResources().getColor(android.R.color.darker_gray));
                   }
               }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        // 提供自定義的布局添加Tab
         for(int i=0;i<4;i++){
             mTabLayout.addTab(mTabLayout.newTab().setCustomView(DataGenerator.getTabView(this,i)));
         }

    }

    private void onTabItemSelected(int position){
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = mFragmensts[0];
                break;
            case 1:
                fragment = mFragmensts[1];
                break;

            case 2:
                fragment = mFragmensts[2];
                break;
            case 3:
                fragment = mFragmensts[3];
                break;
        }
        if(fragment!=null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();
        }
    }
}

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


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文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/tab_menu_home"
        android:icon="@drawable/ic_play_circle_outline_black_24dp"
        android:title="首頁"
        />
    <item
        android:id="@+id/tab_menu_discovery"
        android:icon="@drawable/ic_favorite_border_black_24dp"
        android:title="發現"
        />
    <item
        android:id="@+id/tab_menu_attention"
        android:icon="@drawable/ic_insert_photo_black_24dp"
        android:title="關注"
        />
    <item
        android:id="@+id/tab_menu_profile"
        android:icon="@drawable/ic_clear_all_black_24dp"
        android:title="我的"
        />

</menu>

Activity 代碼如下:

public class BottomNavigationViewActivity extends AppCompatActivity {
    private BottomNavigationView mBottomNavigationView;
    private Fragment []mFragments;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bottom_navigation_view_ac);

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

        initView();
    }

    private void initView() {
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation_view);
        //mBottomNavigationView.getMaxItemCount()

        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                onTabItemSelected(item.getItemId());
                return true;
            }
        });

        // 由於第一次進來沒有回調onNavigationItemSelected,因此需要手動調用一下切換狀態的方法
        onTabItemSelected(R.id.tab_menu_home);
    }

    private void onTabItemSelected(int id){
        Fragment fragment = null;
        switch (id){
            case R.id.tab_menu_home:
                fragment = mFragments[0];
                break;
            case R.id.tab_menu_discovery:
                fragment = mFragments[1];
                break;

            case R.id.tab_menu_attention:
                fragment = mFragments[2];
                break;
            case R.id.tab_menu_profile:
                fragment = mFragments[3];
                break;
        }
        if(fragment!=null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();
        }
    }
}

代碼比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 的實現稍微復雜一點,具體請看代碼,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/home_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <View android:layout_width="match_parent"
          android:layout_height="0.5dp"
          android:alpha="0.6"
          android:background="@android:color/darker_gray"
        />

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_marginTop="3dp"
        android:layout_height="50dp">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            >

        </FrameLayout>
    </android.support.v4.app.FragmentTabHost>
</LinearLayout>

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

Activity 代碼如下:

public class FragmentTabHostActivity extends AppCompatActivity implements TabHost.OnTabChangeListener{
    private Fragment []mFragments;
    private FragmentTabHost mTabHost;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_tab_host_ac_layout);
        mFragments = DataGenerator.getFragments("FragmentTabHost Tab");
        initView();

    }

    private void initView(){
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

        // 關聯TabHost
        mTabHost.setup(this,getSupportFragmentManager(),R.id.home_container);
        //注意,監聽要設置在添加Tab之前
        mTabHost.setOnTabChangedListener(this);


        //添加Tab
        for (int i=0;i<4;i++){
            //生成TabSpec
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTabTitle[i]).setIndicator(DataGenerator.getTabView(this,i));
            // 添加Tab 到TabHost,並綁定Fragment
            Bundle bundle = new Bundle();
            bundle.putString("from","FragmentTabHost Tab");
            mTabHost.addTab(tabSpec,mFragments[i].getClass(),bundle);
        }


        //去掉Tab 之間的分割線
        mTabHost.getTabWidget().setDividerDrawable(null);
        //
        mTabHost.setCurrentTab(0);
    }



    @Override
    public void onTabChanged(String tabId) {
       updateTabState();

    }

    /**
     * 更新Tab 的狀態
     */
    private void updateTabState(){
        TabWidget tabWidget = mTabHost.getTabWidget();
        for (int i=0;i<tabWidget.getTabCount();i++){
            View view = tabWidget.getChildTabViewAt(i);
            ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_content_image);
            TextView  tabText = (TextView) view.findViewById(R.id.tab_content_text);
            if(i == mTabHost.getCurrentTab()){
                tabIcon.setImageResource(DataGenerator.mTabResPressed[i]);
                tabText.setTextColor(getResources().getColor(android.R.color.black));
            }else{
                tabIcon.setImageResource(mTabRes[i]);
                tabText.setTextColor(getResources().getColor(android.R.color.darker_gray));
            }
        }
    }
}

FragmentTabHost 的實現就比前兩個稍微復雜點。首先要通過setup()方法建立FragmentTabHost 與Fragment container的關聯。然后設置Tab切換監聽,添加Tab。需要主要一點,FragmentTabHost 默認在每個Tab之間有一跟豎直的分割先,調用下面這行代碼去掉分割線:

//去掉Tab 之間的分割線 mTabHost.getTabWidget().setDividerDrawable(null);

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

效果如下:


FragmentTabHost.gif

注意:有2點需要注意,1,通過FragmentTabHost添加的Fragment 里面收不到通過 setArgment() 傳遞的參數,要傳遞參數,需要在添加Tab 的時候通過Bundle 來傳參,代碼如下:

 // 添加Tab 到TabHost,並綁定Fragment Bundle bundle = new Bundle(); 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:

  <style name="RadioGroupButtonStyle" >
        <!-- 這個屬性是去掉button 默認樣式-->
        <item name="android:button">@null</item>

        <item name="android:gravity">center</item>
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_weight">1</item>
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">@color/color_selector</item>
    </style>

style 里面定義了RadioButton 的屬性,現在我們直接給RadioButton 設置style 就好了,看先頁面的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/home_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <View android:layout_width="match_parent"
          android:layout_height="0.5dp"
          android:alpha="0.6"
          android:background="@android:color/darker_gray"
        />
    <RadioGroup
        android:id="@+id/radio_group_button"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:gravity="center"
        android:background="@android:color/white"
        >
        <RadioButton
            android:id="@+id/radio_button_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="首頁"
            android:drawableTop="@drawable/tab_home_selector"
            style="@style/RadioGroupButtonStyle"
            />
        <RadioButton
            android:id="@+id/radio_button_discovery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="發現"
            android:drawableTop="@drawable/tab_discovery_selector"
            style="@style/RadioGroupButtonStyle"
            />
        <RadioButton
            android:id="@+id/radio_button_attention"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="關注"
            android:drawableTop="@drawable/tab_attention_selector"
            style="@style/RadioGroupButtonStyle"
            />
        <RadioButton
            android:id="@+id/radio_button_profile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我的"
            android:drawableTop="@drawable/tab_profile_selector"
            style="@style/RadioGroupButtonStyle"
            />
    </RadioGroup>
</LinearLayout>

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

布局文件定義好了之后,看一下Activity 中的代碼:

public class RadioGroupTabActivity extends AppCompatActivity {
    private RadioGroup mRadioGroup;
    private Fragment []mFragments;
    private RadioButton mRadioButtonHome;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.radiogroup_tab_layout);
        mFragments = DataGenerator.getFragments("RadioGroup Tab");
        initView();
    }

    private void initView() {
        mRadioGroup = (RadioGroup) findViewById(R.id.radio_group_button);
        mRadioButtonHome = (RadioButton) findViewById(R.id.radio_button_home);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            Fragment mFragment = null;
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.radio_button_home:
                        mFragment = mFragments[0];
                        break;
                    case R.id.radio_button_discovery:
                        mFragment = mFragments[1];
                        break;
                    case R.id.radio_button_attention:
                        mFragment = mFragments[2];
                        break;
                    case R.id.radio_button_profile:
                        mFragment = mFragments[3];
                        break;
                }
                if(mFragments!=null){
                    getSupportFragmentManager().beginTransaction().replace(R.id.home_container,mFragment).commit();
                }
            }
        });
        // 保證第一次會回調OnCheckedChangeListener
        mRadioButtonHome.setChecked(true);
    }
}

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 代碼下:

public class CustomTabView extends LinearLayout implements View.OnClickListener{
    private List<View> mTabViews;//保存TabView 
    private List<Tab> mTabs;// 保存Tab
    private OnTabCheckListener mOnTabCheckListener;

    public void setOnTabCheckListener(OnTabCheckListener onTabCheckListener) {
        mOnTabCheckListener = onTabCheckListener;
    }

    public CustomTabView(Context context) {
        super(context);
        init();
    }

    public CustomTabView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTabView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CustomTabView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init(){
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);
        mTabViews = new ArrayList<>();
        mTabs = new ArrayList<>();

    }

    /**
     * 添加Tab
     * @param tab
     */
    public void addTab(Tab tab){
        View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab_item_layout,null);
        TextView textView = (TextView) view.findViewById(R.id.custom_tab_text);
        ImageView imageView = (ImageView) view.findViewById(R.id.custom_tab_icon);
        imageView.setImageResource(tab.mIconNormalResId);
        textView.setText(tab.mText);
        textView.setTextColor(tab.mNormalColor);

        view.setTag(mTabViews.size());
        view.setOnClickListener(this);

        mTabViews.add(view);
        mTabs.add(tab);

        addView(view);

    }

    /**
     * 設置選中Tab
     * @param position
     */
    public void setCurrentItem(int position){
        if(position>=mTabs.size() || position<0){
            position = 0;
        }

         mTabViews.get(position).performClick();

        updateState(position);


    }

    /**
     * 更新狀態
     * @param position
     */
    private void updateState(int position){
        for(int i= 0;i<mTabViews.size();i++){
            View view = mTabViews.get(i);
            TextView textView = (TextView) view.findViewById(R.id.custom_tab_text);
            ImageView imageView = (ImageView) view.findViewById(R.id.custom_tab_icon);
            if(i == position){
                imageView.setImageResource(mTabs.get(i).mIconPressedResId);
                textView.setTextColor(mTabs.get(i).mSelectColor);
            }else{
                imageView.setImageResource(mTabs.get(i).mIconNormalResId);
                textView.setTextColor(mTabs.get(i).mNormalColor);
            }
        }
    }


    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        if(mOnTabCheckListener!=null){
            mOnTabCheckListener.onTabSelected(v, position);
        }

        updateState(position);
    }

    public interface  OnTabCheckListener{
        public void onTabSelected(View v,int position);
    }


    public static class Tab{
        private int mIconNormalResId;
        private int mIconPressedResId;
        private int mNormalColor;
        private int mSelectColor;
        private String mText;


        public Tab setText(String text){
            mText = text;
            return this;
        }

        public Tab setNormalIcon(int res){
            mIconNormalResId = res;
            return this;
        }

        public Tab setPressedIcon(int res){
            mIconPressedResId = res;
            return this;
        }

        public Tab setColor(int color){
            mNormalColor = color;
            return this;
        }

        public Tab setCheckedColor(int color){
            mSelectColor = color;
            return this;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mTabViews!=null){
            mTabViews.clear();
        }
        if(mTabs!=null){
            mTabs.clear();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
       // 調整每個Tab的大小
        for(int i=0;i<mTabViews.size();i++){
            View view = mTabViews.get(i);
            int width = getResources().getDisplayMetrics().widthPixels / (mTabs.size());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);

            view.setLayoutParams(params);
        }

    }
}

還是比較簡單,繼承LinearLayout,有一個Tab 類來保存每個tab 的數據,比如圖標,顏色,文字等等,有注釋,就不一一解釋了。

布局文件差不多,其他控件換成CustomTabView 就行,看一下Activity中的代碼:

public class CustomTabActivity extends AppCompatActivity implements CustomTabView.OnTabCheckListener{
    private CustomTabView mCustomTabView;
    private Fragment []mFragmensts;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_tab_ac_layout);
        mFragmensts = DataGenerator.getFragments("CustomTabView Tab");
        initView();

    }

    private void initView() {
        mCustomTabView = (CustomTabView) findViewById(R.id.custom_tab_container);
        CustomTabView.Tab tabHome = new CustomTabView.Tab().setText("首頁")
                .setColor(getResources().getColor(android.R.color.darker_gray))
                .setCheckedColor(getResources().getColor(android.R.color.black))
                .setNormalIcon(R.drawable.ic_tab_strip_icon_feed)
                .setPressedIcon(R.drawable.ic_tab_strip_icon_feed_selected);
        mCustomTabView.addTab(tabHome);
        CustomTabView.Tab tabDis = new CustomTabView.Tab().setText("發現")
                .setColor(getResources().getColor(android.R.color.darker_gray))
                .setCheckedColor(getResources().getColor(android.R.color.black))
                .setNormalIcon(R.drawable.ic_tab_strip_icon_category)
                .setPressedIcon(R.drawable.ic_tab_strip_icon_category_selected);
        mCustomTabView.addTab(tabDis);
        CustomTabView.Tab tabAttention = new CustomTabView.Tab().setText("管制")
                .setColor(getResources().getColor(android.R.color.darker_gray))
                .setCheckedColor(getResources().getColor(android.R.color.black))
                .setNormalIcon(R.drawable.ic_tab_strip_icon_pgc)
                .setPressedIcon(R.drawable.ic_tab_strip_icon_pgc_selected);
        mCustomTabView.addTab(tabAttention);
        CustomTabView.Tab tabProfile = new CustomTabView.Tab().setText("我的")
                .setColor(getResources().getColor(android.R.color.darker_gray))
                .setCheckedColor(getResources().getColor(android.R.color.black))
                .setNormalIcon(R.drawable.ic_tab_strip_icon_profile)
                .setPressedIcon(R.drawable.ic_tab_strip_icon_profile_selected);
        mCustomTabView.addTab(tabProfile);
       //設置監聽
        mCustomTabView.setOnTabCheckListener(this);
       // 默認選中tab
        mCustomTabView.setCurrentItem(0);

    }

    @Override
    public void onTabSelected(View v, int position) {
        Log.e("zhouwei","position:"+position);
        onTabItemSelected(position);
    }

    private void onTabItemSelected(int position){
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = mFragmensts[0];
                break;
            case 1:
                fragment = mFragmensts[1];
                break;

            case 2:
                fragment = mFragmensts[2];
                break;
            case 3:
                fragment = mFragmensts[3];
                break;
        }
        if(fragment!=null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container,fragment).commit();
        }
    }
}

用法很簡單,直接添加Tab ,設置Tab 變換的監聽器和默認選中的Tab 就行。

效果如下:


自定義View CustomTabView 效果.gif

總結:自定義Tab 相比於其他幾種方案還是顯得有些麻煩,但是可以高度定制,喜歡折騰的可以用自定義View 試試。

6 . 總結

本文總結了實現底部導航欄的5種方式,其中TabLayout 和 BottomNavigationView 是Android 5.0 以后添加的新控件,符合Material 設計規范,如果是Materail 風格的,可以考慮用這兩種實現(TabLayout 使用更多的場景其實是頂部帶Indicator的滑動頁卡),其他兩種方式FragmentTabHost 和RadioGroup 也是比較老牌的方式了,在4.x 時代就大量使用,是一般底部導航欄的常規實現。最后就是自定義View來實現了,自定義View稍顯麻煩,但是可定制度高,如果有一些特殊的需求,可以用這種方式來實現。

 

https://blog.csdn.net/qq_23205911/article/details/73430979


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM