//首先bottom依赖
implementation 'com.roughike:bottom-bar:2.0.2'
2.编写bottm bar的xml 是在res 文件夹下 创建xml文件 然后创建xml
这是简化版,可以设置各种属性
<tabs>
<tab
id="@+id/tab_shouye"
title="推荐"
/>
<tab
id="@+id/tab_all"
title="段子"
/>
<tab
id="@+id/tab_cart"
title="发现"
/>
<tab
id="@+id/tab_account"
title="视频"
/>
</tabs>
3.看布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="9"
android:id="@+id/vp"
>
</android.support.v4.view.ViewPager>
<com.roughike.bottombar.BottomBar
android:id="@+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_weight="1"
app:bb_tabXmlResource="@xml/xml"
android:layout_alignParentBottom="true"
/>
</LinearLayout>
view //代码中的fragment可以自己去设置
public class MainActivity extends AppCompatActivity {
private BottomBar bottomBar;
private ViewPager vp;
private ArrayList<Fragment> fragments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp = findViewById(R.id.vp);
bottomBar = findViewById(R.id.bottomBar);
fragments = new ArrayList<>();
fragments.add(new Frgment1());
fragments.add(new Frgment2());
fragments.add(new Frgment3());
vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public int getCount() {
return fragments.size();
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return fragments.get(position);
}
});
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
//滑动时
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//页面选中时
@Override
public void onPageSelected(int position) {
switch (position){
case 0:
bottomBar.selectTabWithId(R.id.tab_shouye);
break;
case 1:
bottomBar.selectTabWithId(R.id.tab_all);
break;
case 2:
bottomBar.selectTabWithId(R.id.tab_cart);
break;
case 3:
bottomBar.selectTabWithId(R.id.tab_account);
break;
}
}
//滑动状态改变时
@Override
public void onPageScrollStateChanged(int state) {
}
});
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelected(int tabId) {
switch (tabId){
case R.id.tab_shouye:
vp.setCurrentItem(0,false);
break;
case R.id.tab_all:
vp.setCurrentItem(1,false);
break;
case R.id.tab_cart:
vp.setCurrentItem(2,false);
break;
case R.id.tab_account:
vp.setCurrentItem(3,false);
break;
}
}
});
}
}
本文详细介绍如何在Android应用中使用BottomBar库实现底部导航栏。从依赖添加到XML配置,再到代码实现,包括ViewPager与BottomBar的联动效果。适用于希望提升应用用户体验的开发者。
1861

被折叠的 条评论
为什么被折叠?



