要在切换到另一个 Fragment 时结束当前 Fragment,可以使用以下步骤:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new AnotherFragment());
fragmentTransaction.commit();
这是一个完整的示例:
public class MyFragment extends Fragment {
// ...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 获取 FragmentManager
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// 结束当前 Fragment
fragmentManager.popBackStack();
// 替换为新的 Fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new AnotherFragment());
fragmentTransaction.commit();
return inflater.inflate(R.layout.fragment_my, container, false);
}
// ...
}
请确保将上述代码中的 R.id.fragment_container
替换为你的布局文件中的容器 ID。