Android实现底部导航栏的主界面
时间: 2023-08-05 17:24:02 浏览: 127
实现底部导航栏的主界面可以通过以下步骤:
1. 在布局文件中添加一个FrameLayout,作为Fragment容器。
2. 在布局文件中添加一个底部导航栏,可以使用BottomNavigationView控件。
3. 创建多个Fragment作为不同的页面,例如首页、分类、购物车、我的等。
4. 在MainActivity中绑定底部导航栏控件,并设置监听器。
5. 在监听器中根据选中的导航项,切换对应的Fragment。
下面是一个示例代码:
activity_main.xml
```
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:menu="@menu/navigation" />
```
MainActivity.java
```
public class MainActivity extends AppCompatActivity {
private Fragment[] fragments = new Fragment[]{
new HomeFragment(),
new CategoryFragment(),
new CartFragment(),
new MeFragment()
};
private int lastSelectedPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BottomNavigationView navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int position = 0;
switch (item.getItemId()) {
case R.id.navigation_home:
position = 0;
break;
case R.id.navigation_category:
position = 1;
break;
case R.id.navigation_cart:
position = 2;
break;
case R.id.navigation_me:
position = 3;
break;
}
if (lastSelectedPosition != position) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.hide(fragments[lastSelectedPosition]);
if (!fragments[position].isAdded()) {
transaction.add(R.id.container, fragments[position]);
}
transaction.show(fragments[position]).commit();
lastSelectedPosition = position;
}
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
for (Fragment fragment : fragments) {
transaction.add(R.id.container, fragment).hide(fragment);
}
transaction.show(fragments[0]).commit();
}
}
```
阅读全文