使用Fragment实现顶部导航功能的代码
时间: 2024-12-17 10:25:23 浏览: 11
在Android中,通常使用`FragmentTransaction`和`FragmentManager`配合`FragmentPagerAdapter`来实现顶部导航的功能,特别是当应用需要支持多种布局结构,而每个布局对应不同的页面内容时。这里是一个简化的示例:
```java
// 首先,定义顶部导航栏(FragmentPagerAdapter)
public class NavAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
// 添加你的Fragment实例到列表
public NavAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
// 在Activity中设置Fragment栈和顶部导航
private NavAdapter navAdapter;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navAdapter = new NavAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(navAdapter);
// 顶部导航栏设置
setupViewPager(viewPager); // 自定义的方法,用于初始化ViewPager的内容
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
// 分别创建并添加各个Fragment
Fragment fragment1 = new Fragment1(); // 替换为实际的Fragment
Fragment fragment2 = new Fragment2(); // 等等...
mFragments.add(fragment1);
mFragments.add(fragment2);
// 当切换顶部导航时,更新对应的Fragment
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition(), true);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// 当其他tab被选择时,隐藏当前显示的fragment
if (viewPager.getCurrentItem() == tab.getPosition()) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStackImmediate();
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
});
}
```
阅读全文