如何在Android中使用BottomNavigationBar实现底部导航
这期内容当中小编将会给大家带来有关如何在Android中使用BottomNavigationBar实现底部导航,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
补充布局文件activity_main
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns: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
importandroid.graphics.Color; importandroid.support.v4.app.FragmentManager; importandroid.support.v4.app.FragmentTransaction; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.util.TypedValue; importandroid.view.Gravity; importandroid.view.View; importandroid.view.ViewGroup; importandroid.widget.FrameLayout; importandroid.widget.ImageView; importandroid.widget.LinearLayout; importandroid.widget.TextView; importcom.ashokvarma.bottomnavigation.BottomNavigationBar; importcom.ashokvarma.bottomnavigation.BottomNavigationItem; importcom.ashokvarma.bottomnavigation.ShapeBadgeItem; importcom.ashokvarma.bottomnavigation.TextBadgeItem; importjava.lang.reflect.Field; publicclassMainActivityextendsAppCompatActivityimplementsBottomNavigationBar.OnTabSelectedListener{ privateFragmentManagermFragmentManager; privateBottomNavigationBarbottomNavigationBar; privateFirstFragmentfirstFragment; privateSecondFragmentsecondFragment; privateThirdFragmentthirdFragment; privateFourthFragmentfourthFragment; //默认选择第一个fragment privateintlastSelectedPosition=0; privateFragmentTransactiontransaction; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottomNavigationBar=this.findViewById(R.id.bottomNavigationBar); showNumberAndShape(); initNavigation(); } /** *初始底部导航栏 */ privatevoidinitNavigation(){ //导航栏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(newBottomNavigationItem(R.drawable.home,"首页") //选中的颜色 .setActiveColor(R.color.colorAccent) //选中的颜色(资源文件下面同上) //.setActiveColorResource(R.color.colorAccent) //未选中的颜色(默认灰色可注释) .setInActiveColor("#999999") //未选中时的图片的资源 .setInactiveIconResource(R.drawable.ic_launcher_background)) .addItem(newBottomNavigationItem(R.drawable.home,"订单") .setActiveColorResource(R.color.colorAccent) .setInActiveColor("#999999") .setInactiveIconResource(R.drawable.ic_launcher_background)). addItem(newBottomNavigationItem(R.drawable.ic_launcher_background,"购物车") .setActiveColorResource(R.color.colorAccent) .setInActiveColor("#999999") .setBadgeItem(textBadgeItem) .setInactiveIconResource(R.drawable.ic_launcher_background)). addItem(newBottomNavigationItem(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 */ privatevoidsetDefaultFragment(){ mFragmentManager=getSupportFragmentManager(); FragmentTransactiontransaction=mFragmentManager.beginTransaction(); firstFragment=newFirstFragment(); transaction.add(R.id.tb,firstFragment); transaction.commit(); } /** *切换事件 */ @Override publicvoidonTabSelected(intposition){ lastSelectedPosition=position;//每次点击赋值 //开启事务 transaction=mFragmentManager.beginTransaction(); hideFragment(transaction); switch(position){ case0: if(firstFragment==null){ firstFragment=newFirstFragment(); transaction.add(R.id.tb,firstFragment); }else{ transaction.show(firstFragment); } //transaction.replace(R.id.tb,firstFragment); break; case1: if(secondFragment==null){ secondFragment=newSecondFragment(); transaction.add(R.id.tb,secondFragment); }else{ transaction.show(secondFragment); } break; case2: if(thirdFragment==null){ thirdFragment=newThirdFragment(); transaction.add(R.id.tb,thirdFragment); }else{ transaction.show(thirdFragment); } break; case3: if(fourthFragment==null){ fourthFragment=newFourthFragment(); transaction.add(R.id.tb,fourthFragment); }else{ transaction.show(fourthFragment); } break; } //事务提交 transaction.commit(); } /** *隐藏当前fragment * *@paramtransaction */ privatevoidhideFragment(FragmentTransactiontransaction){ if(firstFragment!=null){ transaction.hide(firstFragment); } if(secondFragment!=null){ transaction.hide(secondFragment); } if(thirdFragment!=null){ transaction.hide(thirdFragment); } if(fourthFragment!=null){ transaction.hide(fourthFragment); } } privateTextBadgeItemtextBadgeItem; privateShapeBadgeItemshapeBadgeItem; /** *展示消息点 */ privatevoidshowNumberAndShape(){ //消息 textBadgeItem=newTextBadgeItem() .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=newShapeBadgeItem() //也可设置为常量(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:当选中状态时消失,非选中状态显示,morenfalse } @Override publicvoidonTabUnselected(intposition){ } @Override publicvoidonTabReselected(intposition){ } /** *修改间距及图片文字大小 *@parambottomNavigationBar *@paramspace文字与图片的间距 *@paramimgLen单位:dp,图片大小 *@paramtextSize单位:dp,文字大小 */ privatevoidsetIconItemMargin(BottomNavigationBarbottomNavigationBar,intspace,intimgLen,inttextSize){ ClassbarClass=bottomNavigationBar.getClass(); Field[]fields=barClass.getDeclaredFields(); for(inti=0;i<fields.length;i++){ Fieldfield=fields[i]; field.setAccessible(true); if(field.getName().equals("mTabContainer")){ try{ //反射得到mTabContainer LinearLayoutmTabContainer=(LinearLayout)field.get(bottomNavigationBar); for(intj=0;j<mTabContainer.getChildCount();j++){ //获取到容器内的各个Tab Viewview=mTabContainer.getChildAt(j); //获取到Tab内的各个显示控件 FrameLayout.LayoutParamsparams=newFrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(56)); FrameLayoutcontainer=(FrameLayout)view.findViewById(R.id.fixed_bottom_navigation_container); container.setLayoutParams(params); container.setPadding(dip2px(12),dip2px(0),dip2px(12),dip2px(0)); //获取到Tab内的文字控件 TextViewlabelView=(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内的图像控件 ImageViewiconView=(ImageView)view.findViewById(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_icon); //设置图片参数,其中,MethodUtils.dip2px():换算dp值 params=newFrameLayout.LayoutParams(dip2px(imgLen),dip2px(imgLen)); params.setMargins(0,0,0,space/2); params.gravity=Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL; iconView.setLayoutParams(params); } }catch(IllegalAccessExceptione){ e.printStackTrace(); } } } } privateintdip2px(floatdpValue){ finalfloatscale=getApplication().getResources().getDisplayMetrics().density; return(int)(dpValue*scale+0.5f); } }
其中有4个碎片在这只贴出FirstFragment (其余几乎一致)
4、FirstFragment
importandroid.os.Bundle; importandroid.support.annotation.NonNull; importandroid.support.v4.app.Fragment; importandroid.view.LayoutInflater; importandroid.view.View; importandroid.view.ViewGroup; publicclassFirstFragmentextendsFragment{ @Override publicViewonCreateView(@NonNullLayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){ Viewview=inflater.inflate(R.layout.activity_first_fragment,container,false); returnview; } }
注意引用V4的包
其布局:activity_first_fragment
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns: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){ case0: firstFragment=newFirstFragment(); transaction.replace(R.id.tb,firstFragment); break; case1: secondFragment=newSecondFragment(); transaction.replace(R.id.tb,secondFragment); break; case2: thirdFragment=newThirdFragment(); transaction.replace(R.id.tb,thirdFragment); break; case3: fourthFragment=newFourthFragment(); transaction.replace(R.id.tb,fourthFragment); break; }
2)、注释 //hideFragment(transaction);这个方法
6、最后贴出TextBadgeItem和ShapeBadgeItem的属性图
上述就是小编为大家分享的如何在Android中使用BottomNavigationBar实现底部导航了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注恰卡编程网行业资讯频道。
推荐阅读
-
怎么使用Android基准配置文件Baseline Profile方案提升启动速度
-
HTML5如何实现禁止android视频另存为
-
学java好还是学php好?
-
Android如何实现多点触控功能
-
android怎么实现多点触摸应用
-
Android怎么实现手势划定区域裁剪图片
-
android怎么实现简单的矩形裁剪框
-
Android单选多选按钮怎么使用
-
Android中如何利用oncreate获取控件高度或宽度
Android中如何利用oncreate获取控件高度或宽度本篇内容...
-
Android中怎么使用onSaveInstanceState()方法
Android中怎么使用onSaveInstanceState()方法...