Today we use bottomNavigationView+fragment to implement a common bottom switching layout. The following effects
1. First, a simple layout, a fragment and a bottomnavigationview
as follows:
2. A menu menu is needed. Let's implement it. The method is the same as that of the navigation bar menu. You can refer to the previous content (only a new icon is added here)
The code is as follows:
(Find the picture by yourself)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/second_bottomnavigation_home"
android:icon="@drawable/unhome"
android:title="首页" />
<item
android:id="@+id/second_bottomnavigation_news"
android:icon="@drawable/news"
android:title="新闻" />
<item
android:id="@+id/second_bottomnavigation_photo"
android:icon="@drawable/photo"
android:title="图片" />
<item
android:id="@+id/second_bottomnavigation_my"
android:icon="@drawable/my"
android:title="我的" />
</menu>
The navigation bar comes out
Third, realize the click to switch fragment. (Fragment will not be described, please refer to the previous article)
The initialization control is extracted as a global variable
private void initUI() {
// 初始化控件
second_bottomnavigation = findViewById(R.id.second_bottomnavigation);
}
Monitor her state through setOnNavigationItemSelectedListener,
and control the switch by getting id through item, the code is as follows.
private void Listener() {
// 点击事件
second_bottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.second_bottomnavigation_home:
break;
case R.id.second_bottomnavigation_news:
break;
case R.id.second_bottomnavigation_photo:
break;
case R.id.second_bottomnavigation_my:
break;
}
return true;
}
});
}
Then add the switching state of the fragment in the click event.
Fool-like reminder: Be sure to return true
Echoing from the beginning to the end, see the effect-(´∀`;)
ps: Change the theme color by myself, I went to the top navigation bar.
PS: This article uses the method of quotation... Hey