fragment底部导航栏切换实现代码
时间: 2023-10-26 10:19:38 浏览: 110
Fragment导航栏的切换
5星 · 资源好评率100%
以下一个简单的实现底部导航栏切换的示例代码:
```
public class MainActivity extends AppCompatActivity {
private Fragment[] fragments = {new HomeFragment(), new MessageFragment(), new MineFragment()};
private int[] icons = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_mine};
private String[] titles = {"首页", "消息", "我的"};
private int lastIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int index = 0;
switch (item.getItemId()) {
case R.id.action_home:
index = 0;
break;
case R.id.action_message:
index = 1;
break;
case R.id.action_mine:
index = 2;
break;
}
// 判断是否需要切换 Fragment
if (index != lastIndex) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.hide(fragments[lastIndex]);
if (!fragments[index].isAdded()) {
transaction.add(R.id.container, fragments[index]);
}
transaction.show(fragments[index]).commit();
lastIndex = index;
}
return true;
}
});
// 初始化 Fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
for (int i = 0; i < fragments.length; i++) {
transaction.add(R.id.container, fragments[i]);
if (i != 0) {
transaction.hide(fragments[i]);
}
}
transaction.commit();
// 设置底部导航栏图标和文字
for (int i = 0; i < bottomNavigationView.getMenu().size(); i++) {
bottomNavigationView.getMenu().getItem(i).setIcon(icons[i]);
bottomNavigationView.getMenu().getItem(i).setTitle(titles[i]);
}
}
}
```
这里使用了 `BottomNavigationView` 控件来作为底部导航栏。在 `onCreate` 方法中,首先初始化了 `BottomNavigationView`,并设置了其点击事件。当点击不同的菜单项时,会根据当前的索引和点击的索引判断是否需要切换 Fragment。在初始化 Fragment 时,将所有 Fragment 都添加到了 `container` 容器中,并隐藏了除第一个 Fragment 外的其他 Fragment。最后,设置了底部导航栏的图标和文字。
阅读全文