您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關如何在Android中使用BottomNavigationBar實現底部導航,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
補充布局文件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背景圖,防止少圖片資源(效果圖雖不盡人意~)
<img alt="" src="https://img.jbzj.com/file_images/article/201911/2019113134446598.jpg />
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,0,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,0,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的屬性圖
上述就是小編為大家分享的如何在Android中使用BottomNavigationBar實現底部導航了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。