如何在MainActivity中获取随导航栏切换的多个fragment的java文件的实例
时间: 2023-12-03 19:44:15 浏览: 101
您可以通过在MainActivity中使用FragmentManager来获取随导航栏切换的多个Fragment的实例。以下是一个示例代码:
```java
public class MainActivity extends AppCompatActivity {
private Fragment1 fragment1;
private Fragment2 fragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取fragment实例
fragment1 = new Fragment1();
fragment2 = new Fragment2();
// 将fragment添加到FragmentManager中
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, fragment1);
transaction.add(R.id.container, fragment2);
transaction.hide(fragment1);
transaction.hide(fragment2);
transaction.commit();
// 设置导航栏切换监听
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
// 导航栏切换监听
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_fragment1:
showFragment(fragment1);
return true;
case R.id.navigation_fragment2:
showFragment(fragment2);
return true;
}
return false;
}
};
// 显示指定的fragment
private void showFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 隐藏所有fragment
transaction.hide(fragment1);
transaction.hide(fragment2);
// 显示指定的fragment
transaction.show(fragment);
transaction.commit();
}
}
```
在这个示例中,我们创建了两个Fragment实例并将它们添加到FragmentManager中。然后,我们设置导航栏切换监听,当用户点击不同的导航栏选项时,我们调用showFragment方法来显示相应的Fragment。在showFragment方法中,我们使用FragmentManager来隐藏所有Fragment并显示指定的Fragment。
阅读全文