1. 程式人生 > 程式設計 >Android BottomNavigationBar底部導航的使用方法

Android BottomNavigationBar底部導航的使用方法

簡介:Google推出的BottomNavigationBar底部導航欄

1 、基本的使用(add和replace方式)
2、擴充套件新增訊息和圖形
3、修改圖片大小與文字間距

版本更新:2019-5-13

補充佈局檔案activity_main

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

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

  <View
    android:layout_width="match_parent"
    android:layout_height="0.5dp"
    android:background="#eeeeee" />

  <com.ashokvarma.bottomnavigation.BottomNavigationBar
    android:id="@+id/bottom_navigation_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" />

</LinearLayout>

1、預設使用studio背景圖,防止少圖片資源(效果圖雖不盡人意~)


2、專案build.gradle新增依賴:(注意studio3.0以下將implementation 換成 compile)

implementation 'com.ashokvarma.android:bottom-navigation-bar:2.0.4'

3、MainActivity

import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.ShapeBadgeItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {

  private FragmentManager mFragmentManager;
  private BottomNavigationBar bottomNavigationBar;

  private FirstFragment firstFragment;
  private SecondFragment secondFragment;
  private ThirdFragment thirdFragment;
  private FourthFragment fourthFragment;
  //預設選擇第一個fragment
  private int lastSelectedPosition = 0;
  private FragmentTransaction transaction;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bottomNavigationBar = this.findViewById(R.id.bottomNavigationBar);
    showNumberAndShape();
    initNavigation();
  }

  /**
   * 初始底部導航欄
   */
  private void initNavigation() {
    //導航欄Item的個數<=3 用 MODE_FIXED 模式,否則用 MODE_SHIFTING 模式
    bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
    bottomNavigationBar.setTabSelectedListener(this);//監聽切換點選事件
    //bottomNavigationBar.setBarBackgroundColor("#595757");//背景顏色
    //1、BACKGROUND_STYLE_DEFAULT:如果設定的Mode為MODE_FIXED,將使用BACKGROUND_STYLE_STATIC 。如果Mode為MODE_SHIFTING將使用BACKGROUND_STYLE_RIPPLE。
    //2、BACKGROUND_STYLE_STATIC:點選無水波紋效果
    //3、BACKGROUND_STYLE_RIPPLE:點選有水波紋效果
    bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
    //需要新增的item數
    bottomNavigationBar
        //選中時的圖片的資源、文字
        .addItem(new BottomNavigationItem(R.drawable.home,"首頁")
            //選中的顏色
            .setActiveColor(R.color.colorAccent)
            //選中的顏色(資原始檔 下面同上)
            //.setActiveColorResource(R.color.colorAccent)
            //未選中的顏色(預設灰色 可註釋)
            .setInActiveColor("#999999")
            //未選中時的圖片的資源
            .setInactiveIconResource(R.drawable.ic_launcher_background))
        .addItem(new BottomNavigationItem(R.drawable.home,"訂單")
            .setActiveColorResource(R.color.colorAccent)
            .setInActiveColor("#999999")
            .setInactiveIconResource(R.drawable.ic_launcher_background)).
        addItem(new BottomNavigationItem(R.drawable.ic_launcher_background,"購物車")
            .setActiveColorResource(R.color.colorAccent)
            .setInActiveColor("#999999")
            .setBadgeItem(textBadgeItem)
            .setInactiveIconResource(R.drawable.ic_launcher_background)).
        addItem(new BottomNavigationItem(R.drawable.ic_launcher_background,"我的")
            .setActiveColorResource(R.color.colorAccent)
            .setInActiveColor("#999999")
            .setBadgeItem(shapeBadgeItem)
            .setInactiveIconResource(R.drawable.ic_launcher_background))
        .setFirstSelectedPosition(lastSelectedPosition)//設定預設選中項
        //.setFab(FloatingActionButton的id)//FloatingActionButton 關聯
        .initialise();//注意此句放在最後
    setIconItemMargin(bottomNavigationBar,10,25,14);
    setDefaultFragment();
  }

  /**
   * 設定預設開啟的fragment
   */
  private void setDefaultFragment() {
    mFragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = mFragmentManager.beginTransaction();
    firstFragment = new FirstFragment();
    transaction.add(R.id.tb,firstFragment);
    transaction.commit();
  }

  /**
   * 切換事件
   */
  @Override
  public void onTabSelected(int position) {
    lastSelectedPosition = position;//每次點選賦值
    //開啟事務
    transaction = mFragmentManager.beginTransaction();
    hideFragment(transaction);
    switch (position) {
      case 0:
        if (firstFragment == null) {
          firstFragment = new FirstFragment();
          transaction.add(R.id.tb,firstFragment);
        } else {
          transaction.show(firstFragment);
        }
        // transaction.replace(R.id.tb,firstFragment);
        break;
      case 1:
        if (secondFragment == null) {
          secondFragment = new SecondFragment();
          transaction.add(R.id.tb,secondFragment);
        } else {
          transaction.show(secondFragment);
        }
        break;
      case 2:
        if (thirdFragment == null) {
          thirdFragment = new ThirdFragment();
          transaction.add(R.id.tb,thirdFragment);
        } else {
          transaction.show(thirdFragment);
        }
        break;
      case 3:
        if (fourthFragment == null) {
          fourthFragment = new FourthFragment();
          transaction.add(R.id.tb,fourthFragment);
        } else {
          transaction.show(fourthFragment);
        }
        break;
    }
    // 事務提交
    transaction.commit();
  }

  /**
   * 隱藏當前fragment
   *
   * @param transaction
   */
  private void hideFragment(FragmentTransaction transaction) {
    if (firstFragment != null) {
      transaction.hide(firstFragment);
    }
    if (secondFragment != null) {
      transaction.hide(secondFragment);
    }
    if (thirdFragment != null) {
      transaction.hide(thirdFragment);
    }
    if (fourthFragment != null) {
      transaction.hide(fourthFragment);
    }
  }

  private TextBadgeItem textBadgeItem;
  private ShapeBadgeItem shapeBadgeItem;

  /**
   * 展示訊息點
   */
  private void showNumberAndShape() {
    //訊息
    textBadgeItem = new TextBadgeItem()
        .setText("99")//顯示的文字
        .setTextColor("#ffffff")//文字顏色
        //.setTextColorResource(R.color.colorAccent)//文字顏色(資原始檔-下面如同)
        .setBorderWidth(6)//圓環寬度
        .setBorderColor(Color.parseColor("#000000"))//圓環燕色
        //.setBorderColorResource(R.color.colorPrimary)
        .setBackgroundColor("#FF4081")//背景顏色
        .setHideOnSelect(false);//選中是否隱藏
    //.setBackgroundColorResource(R.color.colorAccent)//背景顏色
    //.setAnimationDuration(300)//隱藏與動畫的過渡時間(setHideOnSelect 為true時生效)
    //.setGravity(Gravity.RIGHT | Gravity.TOP); //位置,預設右上角(可不設定)

    //形狀
    shapeBadgeItem = new ShapeBadgeItem()
        //也可設定為常量 (0-6之間)
        .setShape(ShapeBadgeItem.SHAPE_HEART) //形狀
        .setShapeColor(Color.RED) //顏色
        //.setShapeColorResource(R.color.colorPrimaryDark) //(同上)
        .setEdgeMarginInDp(this,0) //距離Item的邊距,dp值
        //.setEdgeMarginInPixels(20) //距離Item的邊距,px
        .setSizeInDp(this,15,15) //寬高值,dp
        //.setSizeInPixels(30,30) //寬高值,px
        .setAnimationDuration(300) //隱藏和展示的動畫速度,單位毫秒,和setHideOnSelect一起使用
        //.setGravity(Gravity.LEFT) //位置,預設右上角
        .setHideOnSelect(false); //true:當選中狀態時消失,非選中狀態顯示,moren false
  }

  @Override
  public void onTabUnselected(int position) {
  }

  @Override
  public void onTabReselected(int position) {
  }

  /**
   * 修改間距及圖片文字大小
   * @param bottomNavigationBar
   * @param space 文字與圖片的間距
   * @param imgLen 單位:dp,圖片大小
   * @param textSize 單位:dp,文字大小
   */
  private void setIconItemMargin(BottomNavigationBar bottomNavigationBar,int space,int imgLen,int textSize){
    Class barClass = bottomNavigationBar.getClass();
    Field[] fields = barClass.getDeclaredFields();
    for(int i = 0; i < fields.length; i++){
      Field field = fields[i];
      field.setAccessible(true);
      if(field.getName().equals("mTabContainer")){
        try{
          //反射得到 mTabContainer
          LinearLayout mTabContainer = (LinearLayout) field.get(bottomNavigationBar);
          for(int j = 0; j < mTabContainer.getChildCount(); j++){
            //獲取到容器內的各個Tab
            View view = mTabContainer.getChildAt(j);
            //獲取到Tab內的各個顯示控制元件
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(56));
            FrameLayout container = (FrameLayout) view.findViewById(R.id.fixed_bottom_navigation_container);
            container.setLayoutParams(params);
            container.setPadding(dip2px(12),dip2px(0),dip2px(12),dip2px(0));

            //獲取到Tab內的文字控制元件
            TextView labelView = (TextView) view.findViewById(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_title);
            //計算文字的高度DP值並設定,setTextSize為設定文字正方形的對角線長度,所以:文字高度(總內容高度減去間距和圖片高度)*根號2即為對角線長度,此處用DP值,設定該值即可。
            labelView.setTextSize(TypedValue.COMPLEX_UNIT_DIP,textSize);
            labelView.setIncludeFontPadding(false);
            labelView.setPadding(0,dip2px(20-textSize - space/2));

            //獲取到Tab內的影象控制元件
            ImageView iconView = (ImageView) view.findViewById(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_icon);
            //設定圖片引數,其中,MethodUtils.dip2px():換算dp值
            params = new FrameLayout.LayoutParams(dip2px(imgLen),dip2px(imgLen));
            params.setMargins(0,space/2);
            params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
            iconView.setLayoutParams(params);
          }
        } catch (IllegalAccessException e){
          e.printStackTrace();
        }
      }
    }
  }

  private int dip2px(float dpValue) {
    final float scale = getApplication().getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
  }
}

其中有4個碎片在這隻貼出FirstFragment (其餘幾乎一致)

4、FirstFragment

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

  @Override
  public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_first_fragment,container,false);

    return view;
  }
}

注意引用V4的包

其佈局:activity_first_fragment

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

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="第一個Fragment"
    android:textSize="30sp" />
</LinearLayout>

5、若要使用replace的顯示方式,將onTabSelected監聽處改為如下程式碼即可

1)、switch處

 switch (position) {
      case 0:
        firstFragment = new FirstFragment();
        transaction.replace(R.id.tb,firstFragment);
        break;
      case 1:
        secondFragment = new SecondFragment();
        transaction.replace(R.id.tb,secondFragment);
        break;
      case 2:
        thirdFragment = new ThirdFragment();
        transaction.replace(R.id.tb,thirdFragment);
        break;
      case 3:
        fourthFragment = new FourthFragment();
        transaction.replace(R.id.tb,fourthFragment);
        break;
    }

2)、註釋 //hideFragment(transaction);這個方法

6、最後貼出TextBadgeItem和ShapeBadgeItem的屬性圖

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。