安卓底部导航栏fragment
时间: 2023-07-29 20:11:03 浏览: 150
Android程序开发之Fragment实现底部导航栏实例代码
安卓底部导航栏通常使用Fragment来实现切换不同的页面。下面是一个简单的示例代码,展示如何在底部导航栏中使用Fragment:
1. 首先,在布局文件中定义底部导航栏的样式,例如使用`BottomNavigationView`:
```xml
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="@menu/bottom_navigation_menu" />
```
2. 创建一个`menu`文件夹,并在其中创建一个`bottom_navigation_menu.xml`文件,定义底部导航栏的菜单项:
```xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_home"
android:title="Home"
android:icon="@drawable/ic_home" />
<item
android:id="@+id/menu_dashboard"
android:title="Dashboard"
android:icon="@drawable/ic_dashboard" />
<item
android:id="@+id/menu_notifications"
android:title="Notifications"
android:icon="@drawable/ic_notifications" />
</menu>
```
3. 在Activity中设置底部导航栏的点击监听和Fragment切换逻辑:
```java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private FragmentManager fragmentManager;
private Fragment currentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_navigation);
fragmentManager = getSupportFragmentManager();
// 默认显示第一个Fragment
currentFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentFragment).commit();
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home:
currentFragment = new HomeFragment();
break;
case R.id.menu_dashboard:
currentFragment = new DashboardFragment();
break;
case R.id.menu_notifications:
currentFragment = new NotificationsFragment();
break;
}
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentFragment).commit();
return true;
}
});
}
}
```
4. 创建对应的Fragment类,例如`HomeFragment`、`DashboardFragment`和`NotificationsFragment`,并实现各自的布局和逻辑。
这样,当底部导航栏的菜单项被点击时,对应的Fragment就会被加载到`fragment_container`容器中,实现了底部导航栏的切换效果。
阅读全文