我想要这种类型的设计 :: 这是我的设计
我的 mainactivity.xml 仅包含一个 frameLayout,它被底部栏菜单项中的选定片段替换。
它的代码在这里:
b = BottomBar.attach(this,savedInstanceState);
b.setItemsFromMenu(R.xml.menu_main, new OnMenuTabClickListener() {
@Override
public void onMenuTabSelected(@IdRes int menuItemId) {
if(menuItemId == R.id.BottomBarItemOne){
PeopleFragment p = new PeopleFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,p).commit();
}
else if(menuItemId == R.id.BottomBarItemTwo){
LocationFragment l = new LocationFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,l).commit();
}
else if(menuItemId == R.id.BottomBarItemThree){
HistoryFragment h = new HistoryFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,h).commit();
}
else if(menuItemId == R.id.BottomBarItemFour){
LikesFragment li = new LikesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,li).commit();
}
}
现在我想在其中一个 Fragment 上创建一个 tabview:为此,我在所需的 Fragment xml 文件中实现了工具栏、tablayout 和 viewpager。我创建了一个单独的 java 文件,其中包含 viewPagerAdapter 类。
public class viewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>(); // this line can cause crashes
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragment(Fragment fragment,String tabTitle){
fragments.add(fragment); // this line can cause crashes
tabTitles.add(tabTitle);
}
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
现在我想添加这段代码来实现tablayout ::
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new viewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new HomeFragment(),"Home"); // this line can cause crashes
viewPagerAdapter.addFragment(new MessageFragment(),"Message"); // this line can cause crashes
viewPagerAdapter.addFragment(new ContectFragment(),"Contect"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
在 Fragment 的 onCreate 方法中给出如下::
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TabLyout Code Here
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
但 Android Studio 不允许在 Fragment 中使用 Tablayout Fragment 代码。
我能做些什么 ?如何在其中一个片段中实现 tablayout?