从其他活动回到同一片段时,如何保存和恢复片段中RecyclerView的滚动位置?

时间:2018-10-01 09:08:04

标签: android android-fragments android-recyclerview

对主持人的要求:这不是重复的问题,请阅读以下信息。

在问这个问题之前,我已经尝试了几乎所有可用的SO解决方案,但是没有一个对我有用,有的导致崩溃而有的根本不起作用(我是初学者,有可能我在我的代码中做错了什么,我不怪任何人在SO上无法得到的答案都无法解决我的问题)。下面是我的代码,请看一下:

fragment_tab1.xml(包含recyclerview):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="#333333"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="96dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="42dp"
            android:background="@color/colorPrimaryDark"

            android:id="@+id/sort1"
            android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/sort"
            android:layout_marginLeft="10dp"
            android:fontFamily="@font/quicksand"
            android:textStyle="bold"
            android:text="Sort by:"
            android:textColor="#ffffff"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                style="@style/Widget.AppCompat.Button.Colored"
                android:text="Oldest first"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.Button.Colored"
            android:text="Newest first"/>
        </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_below="@id/sort1"
        android:clipToPadding="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:padding="5dp" />

    </RelativeLayout>

</LinearLayout>

Fragmenttab1.java

public class tab1  extends Fragment {
    RecyclerView mRecyclerView;
    FirebaseDatabase mFirebaseDatabase;
    DatabaseReference mRef;
    LinearLayoutManager manager;
    private static final String TAG = "tab1";
    ProgressDialog progressDialog;
    View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //Returning the layout file after inflating
        //Change R.layout.tab1 in you classes
         rootView = inflater.inflate(R.layout.fragment_tab1, container, false);


return rootView;

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);



        manager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setItemViewCacheSize(20);
        mRecyclerView.setDrawingCacheEnabled(true);
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mRef = mFirebaseDatabase.getReference("memes");

        mFirebaseDatabase.getInstance().getReference().keepSynced(true);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Please Wait");
        progressDialog.show();

    }

    public void onStart() {

        super.onStart();


        FirebaseRecyclerAdapter<Model, ViewHolder> firebaseRecyclerAdapter =
                new FirebaseRecyclerAdapter<Model, ViewHolder>(
                        Model.class,
                        R.layout.row2,
                        ViewHolder.class,
                        mRef

                ) {



                    @Override
                    protected void populateViewHolder(ViewHolder viewHolder, Model model, int position) {
                        viewHolder.setDetails(getActivity(), model.getTitle(), model.getDesc(), model.getImage());
                        progressDialog.cancel();
                    }



                    @Override
                    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                        ViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);

                        viewHolder.setOnClickListener(new ViewHolder.ClickListener(){




                            @Override
                            public void onItemClick(View view, int position){



                                //get data from firebase here
                                String mTitle = getItem(position).getTitle();
                                String mDesc= getItem(position).getDesc();
                                String mImage = getItem(position).getImage();

                                //pass this data to new activity
                                Intent intent = new Intent(view.getContext(), ArticleDetail.class);
                                intent.putExtra("title", mTitle);// put title
                                intent.putExtra("desc", mDesc);// put description
                                intent.putExtra("image", mImage); //put image urls

                                startActivity(intent);
                            }




                            @Override
                            public void onItemLongClick(View view, int position){

                                //TODO your own implementation on long item click


                            }

                        });

                        return viewHolder;
                    }
                };


        mRecyclerView.setAdapter(firebaseRecyclerAdapter);

    }

    @Override
    public void  onPause() {
        super.onPause();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        View firstChild = mRecyclerView.getChildAt(0);
        int firstVisiblePosition = mRecyclerView.getChildAdapterPosition(firstChild);
        int offset = firstChild.getTop();

        Log.d(TAG, "Postition: " + firstVisiblePosition);
        Log.d(TAG, "Offset: " + offset);

        preferences.edit()
                .putInt("position", firstVisiblePosition)
                .putInt("offset", offset)
                .apply();
    }


    @Override
    public void onResume(){
        super.onResume();

    }
    @Override
    public void onSaveInstanceState(Bundle outState) {


        super.onSaveInstanceState(outState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {


        super.onViewStateRestored(savedInstanceState);
    }

}

4 个答案:

答案 0 :(得分:0)

您应该使用此方法返回可见的第一项:

int findFirstVisibleItemPosition();

然后必须将该索引保存在onPause()上,当用户返回检索时,将其设置在onResume()上:

void scrollToPosition (int position)

答案 1 :(得分:0)

花了这么多天,尝试了许多解决方案之后,终于有了https://stackoverflow.com/a/42563804/2128364

为我的问题找到了可行的解决方案

我已将工作解决方案移至另一种方法以使其在片段中起作用。

也许这可以节省某人的生活,这是它的工作原理:

  1. onConfigurationChanged(如原始解决方案中所述),onSaveInstanceState或onViewRestoredState方法不起作用,因此您需要onPause和onResume方法分别保存和恢复状态。
  2. 您必须使用onPause方法保存状态:

    mBundleRecyclerViewState = new Bundle();    
    
    mListState = mRecyclerView.getLayoutManager().onSaveInstanceState();
    
    mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, mListState);
    
  3. 然后使用onResume方法还原它:

       if (mBundleRecyclerViewState != null) {
            new Handler().postDelayed(new Runnable() {
    
                @Override
                public void run() {
                    mListState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
                    mRecyclerView.getLayoutManager().onRestoreInstanceState(mListState);
    
                }
            }, 50);
        }
    
    
        mRecyclerView.setLayoutManager(staggeredGridLayoutManager);
    

答案 2 :(得分:0)

如果还没有,请在您的recyclerView中添加build.gradle依赖项

implementation "androidx.recyclerview:recyclerview:1.2.0-alpha05"

比在初始化列表适配器之后才设置stateRestorationPolicy

 listAdapter = ListAdapter()

 // Set scroll restore policy
 listdapter.stateRestorationPolicy =
      RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

有关stateRestorationPolicy和不同类型的策略visit this article

的更多信息

答案 3 :(得分:-1)

尝试使用MVVM体系结构。使用ViewModel,因此保存的数据不依赖于生命周期。同时查看LiveData以对ViewModel的变化做出反应。