我有两个标签。在其中一个选项卡中,有一个片段(比如fragment1),其中包含项目的网格视图。如果用户单击网格项,则需要显示新片段(比如fragment2),在后台堆栈中添加旧片段。但是我对替换片段感到磕磕绊绊。点击后,再次出现相同的fragment1。
activity_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="in.brewtv.activities.HomeActivity">
<android.support.design.widget.AppBarLayout
...>
...
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
HomeActivity.class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return MyFeedFragment.newInstance();
case 1:
return CategoriesFragment.newInstance();
}
return null;
}
...
CategoriesGridDataAdapter.class:
CategoriesItemsRowHolder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment newFragment = SingleCategoryFragment.newInstance(category);
FragmentTransaction transaction = ((Activity) mContext).getFragmentManager().beginTransaction();
transaction.replace(R.id.categories_recycler_view_layout, newFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
我做错了什么?我该如何纠正?