BottomNavigationView是design包下面的一个控件, Android Support Library 25 中才增加了 这么个控件。BottomNavigationView顾名思义是一个地步导航栏控件,接下来将说说一下BottomNavigationView的使用:
BottomNavigationView+Fragment
Android开发中最常见的界面就是底部一个导航栏,并配上几个Fragment,实现页面切换的效果:
效果:
- 核心代码:
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation_view"
android:layout_width="0dp"
android:layout_height="50dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:itemBackground="@color/colorRed"
app:itemTextColor="@color/colorWhite"
app:itemIconTint="@color/colorWhite"
app:menu="@menu/menu"
/>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag);
navigationView = (BottomNavigationView)findViewById(R.id.navigation_view);
// 重新点击监听(即点击目前选中的Tab时触发)
navigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
@Override
public void onNavigationItemReselected(@NonNull MenuItem item) {
Log.e("ee","Reselected Item:"+item.getTitle());
}
});
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Log.e("ee","Selected Item:"+item.getTitle());
onTabSelected(item.getItemId());
return true;
}
});
onTabSelected(R.id.tab_home);
}
private void onTabSelected(int id){
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = null;
switch (id){
case R.id.tab_home:
fragment = new HomeFragment();
break;
case R.id.tab_message:
fragment = new MessageFragment();
break;
case R.id.tab_player:
fragment = new PlayerFragment();
break;
case R.id.tab_more:
fragment = new MineFragment();
break;
}
transaction.replace(R.id.container,fragment);
transaction.commit();
}