当前,我的应用程序具有底部导航菜单,并且该菜单中的每个项目都有不同的选项卡菜单。
我在一个标签页中有一个按钮,我希望当用户单击该按钮时,显示一个新的片段。但是,因为它是选项卡菜单,所以片段是通过ViewPager显示的,我不知道如何以这种方式打开新的片段。我试图替换ViewPager,但是没有成功,当我按下按钮时什么也没出现。
1st-ProfessionalFragment(当我单击底部导航菜单时打开的片段。这是我实例化ViewPager的位置)
2nd-EducationFragment(此片段是ProfessionalFragment的“菜单”选项卡的一个选项卡。这是具有打开新片段的按钮的片段)
3rd-BasicCoursesFragment(这是我想通过单击EducationFragment中的按钮打开的片段)
以下是代码:
ProfessionalFragment
public class ProfessionalFragment extends Fragment {
private ProfessionalViewModel dashboardViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
ViewModelProviders.of(this).get(ProfessionalViewModel.class);
View root = inflater.inflate(R.layout.fragment_professional, container, false);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getChildFragmentManager());
ViewPager viewPager = root.findViewById(R.id.viewPagerProfessional);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = root.findViewById(R.id.tabsProfessional);
tabs.setupWithViewPager(viewPager);
return root;
}
}
class SectionsPagerAdapter extends FragmentPagerAdapter {
@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.title_work, R.string.title_education};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new WorkFragment();
break;
case 1:
fragment = new EducationFragment();
break;
}
return fragment;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
return 2;
}
}
EducationFragment
public class EducationFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_education, container, false);
Button basicCourses = root.findViewById(R.id.button_basic_courses);
basicCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
BasicCoursesFragment basicCoursesFragment = new BasicCoursesFragment();
ft.replace(R.id.viewPagerProfessional, basicCoursesFragment);
ft.addToBackStack(null);
ft.commit();
}
});
return root;
}
}
我将非常感谢您的帮助。
您可以使用接口使EducationFragment
片段与activity
进行通信。检查此链接Communicate with activity。然后,可以将包含ProfessionalFragment
片段的容器替换为目标片段BasicCoursesFragment
。将以下内容移到您的活动中
FragmentTransaction ft = getFragmentManager().beginTransaction();
BasicCoursesFragment basicCoursesFragment = new BasicCoursesFragment();
ft.replace(/** Replace this with the container that contain ProfessionalFragment*/, basicCoursesFragment);
ft.addToBackStack(null);
ft.commit();