我有一个tabLayout,附带4个四个标签(片段),并附有活动内FragmentPagerAdapter的支持。
我想使用附加的导航视图导航到标签页。单击导航视图中的项目时如何转到选项卡。
然后如何使用新片段删除当前的四个选项卡(使用tablayout附加)。
附加碎片:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OfferFragment(), "OFFERS");
adapter.addFragment(new BookedHistoryFragment(), "Booked History");
adapter.addFragment(new ReviewFragment(), "Reviews");
adapter.addFragment(new AvailableRoomFragment(), "Available");
viewPager.setAdapter(adapter);
}
Sub classAdapter添加片段。
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
导航视图操作:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_offers) {
int tabCount= tabLayout.getTabCount();
// I want to move to other tab.
Toast.makeText(getApplicationContext(),"First",Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(getApplicationContext(), Booking.class);
// startActivity(intent);
}
else if (menuItem.getItemId() == R.id.nav_item_avail_room) {
// Then I want to remove Four tabs and call a new fragment.
Toast.makeText(getApplicationContext(),"Second",Toast.LENGTH_SHORT).show();
}
return false;
}
});
答案 0 :(得分:0)
在导航视图中单击项目时,只需告诉选项卡索引。代码如下。
对于第二个问题,我开始了新的活动并附加了片段。
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_offers) {
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
}
else if (menuItem.getItemId() == R.id.nav_item_avail_room) {
// Here I started a new activity and attached fragment.
}
return false;
}
});