将RecyclerView状态保存在另一个Fragment内创建的ViewPager中的Fragment中

时间:2017-02-15 13:35:18

标签: android android-fragments

我在ViewPager

中有一个Fragment
public class FragmentPager extends BaseFragment {

    @Bind(R.id.viewpager)
    ViewPager viewPager;
    @Bind(R.id.detail_tabs)
    TabLayout detailTabs;

    private Activity mActivity;
    private PagerAdapter mPagerAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mPagerAdapter = new PagerAdapter(getChildFragmentManager());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager, container, false);

        ButterKnife.bind(this, v);

        viewPager.setAdapter(mPagerAdapter);
        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        viewPager.setPageMargin(pageMargin);
        detailTabs.setupWithViewPager(viewPager);


        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}

我已经使用FragmentStatePagerAdapter来管理ViewPager中的片段。每个片段都有一个RecyclerView。点击RecyclerView的每个项目后,我将FragmentPager替换为FragmentDetail。当我导航回FragmentPager时,RecyclerView从头开始而不是滚动位置。

1 个答案:

答案 0 :(得分:0)

我认为您使用fragmentTransaction替换方法更改了您的片段。您需要使用fragmentTransaction add方法执行此操作。见下文

Basic difference between add() and replace() method of Fragment