如何在片段中保存recyclerview的滚动位置

时间:2017-07-26 02:09:17

标签: android android-recyclerview position

我从这里听了很多答案..但没有一个解决我的问题..这就是我要问的原因。

我想在片段中保存滚动位置。 在他们建议遵循的许多文章中

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

但这两种方法在片段中不可用。

我的代码:

private int mPositionIng = RecyclerView.NO_POSITION;

private String KEY_POSITION_ING = "KeyPositionIng";
在OnCreateView()

if (savedInstanceState != null) {

            if (savedInstanceState.containsKey(KEY_POSITION_ING)) {
                mPositionIng = savedInstanceState.getInt(KEY_POSITION_ING);
            }
}

片段中的覆盖方法它们与上面的方法不同。我不知道我在哪里做错了。

@Override
    public void onSaveInstanceState(Bundle outState) {

        int scrollPositionIng = mRecyclerViewIngredients.computeVerticalScrollOffset();

        mPositionIng = scrollPositionIng;

        outState.putInt(KEY_POSITION_ING, mPositionIng);
        super.onSaveInstanceState(outState);
    }

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

        if (mPositionIng != RecyclerView.NO_POSITION) {

            mRecyclerViewIngredients.getLayoutManager().scrollToPosition(mPositionIng);
        }


        super.onViewStateRestored(savedInstanceState);
    }

我只需要在方向改变时保存滚动位置..请帮忙。 任何建议都会有所帮助。感谢......

2 个答案:

答案 0 :(得分:1)

更新

我在下面写的所有内容都是正确的,但它不适合你的原因是我没有意识到你的Activity布局是如何构建的。这是您的Activity布局(略微清理):

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.tapan.recipemaster.activity.RecipeDetailActivity">
    
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
    
                <FrameLayout
                    android:id="@+id/fl_fragment_detail"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:padding="@dimen/padding_10dp"/>
    
            </RelativeLayout>
    
        </ScrollView>
    
    </android.support.constraint.ConstraintLayout>

同时,这是你Fragment的布局(再次,稍微清理一下):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tapan.recipemaster.fragment.RecipeDetailFragment">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="@dimen/padding_10dp"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorAccent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_ingredient"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#FFF"
                    android:textSize="@dimen/text_23sp"
                    android:text="Ingredients"/>

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/rv_ingredients"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/dimen_8dp"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_step"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/dimen_8dp"
                    android:textColor="@color/colorPrimaryDark"
                    android:textSize="@dimen/text_23sp"
                    android:text="Steps"/>

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/rv_steps"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/dimen_8dp"/>

            </LinearLayout>

        </LinearLayout>

    </ScrollView>

</FrameLayout>

两个RecyclerView都有android:layout_height="wrap_content",这意味着它们不会滚动。相反,ScrollView中的Activity是提供滚动行为的视图,因此视图必须保存其滚动位置。

您可以让系统为此ScrollView提供此ID。您想要的任何ID,只要它是唯一的。您根本不必编写任何Java。

<ScrollView
    android:id="@+id/thisfixestheproblem"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

确保您修改了活动布局中的ScrollView,而不是片段布局中的RecyclerView

原始

您发布的所有代码均无需保存RecyclerView在方向更改时的滚动位置。只要Fragment在您的布局中有唯一的ID,它就会自动为您保存滚动位置。

这是一个非常小的示例应用程序,显示自动保存滚动位置,即使动态添加public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("buttonVisible", button.getVisibility() == View.VISIBLE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getSupportFragmentManager() .beginTransaction() .replace(R.id.content, new MyFragment()) .commit(); button.setVisibility(View.GONE); } }); if (savedInstanceState != null) { boolean buttonVisible = savedInstanceState.getBoolean("buttonVisible"); button.setVisibility(buttonVisible ? View.VISIBLE : View.GONE); } } } 。正如您所看到的,我自己保存的唯一实例状态是启动片段的按钮是否应该可见。

<强> MainActivity.java

public class MyFragment extends Fragment {

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

        RecyclerView recycler = (RecyclerView) root.findViewById(R.id.recycler);
        recycler.setAdapter(new MyAdapter());

        return root;
    }

    private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View itemView = inflater.inflate(R.layout.itemview, parent, false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Drawable d = new ColorDrawable(Color.argb(0xff, 0, 0, position));
            ViewCompat.setBackground(holder.image, d);
            holder.text.setText("" + position);
        }

        @Override
        public int getItemCount() {
            return 256;
        }
    }

    private static class MyViewHolder extends RecyclerView.ViewHolder {

        final View image;
        final TextView text;

        MyViewHolder(View itemView) {
            super(itemView);

            this.image = itemView.findViewById(R.id.image);
            this.text = (TextView) itemView.findViewById(R.id.text);
        }
    }
}

<强> MyFragment.java

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="create fragment"/>

</FrameLayout>

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="android.support.v7.widget.LinearLayoutManager"
    tools:listitem="@layout/itemview"/>

<强> myfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <View
        android:id="@+id/image"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_margin="12dp"
        tools:background="#333"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:text="text"/>

</LinearLayout>

<强> itemview.xml

for i in ['onE','TwO','ThRee', 'FOur']:
    print(i)
    df['new_number'] = df['number'].str.replace(i,'')

答案 1 :(得分:0)

让Android操作系统为您处理,在您想要的标记活动中AndroidManifest.xml添加:

android:configChanges="orientation|screenSize"