当我们通过单击 RecyclerView 中的项目列表转到 Detail Activity 时保存 RecyclerView 的位置,并在我们返回 RecyclerView 时恢复它

Save Position of RecylerView when we go to Detail Activity by clicking from list of items in RecyclerView and restore it when we back to RecylerView

如何使用 RecyclerView 中项目列表中的 itemclicklistener(这些项目是从 Firebase JSON 检索到的)转到下一个详细信息 Activity 时如何保存 RecylerView Activity 的滚动位置当我们回到 Recylerview Activity 并且我正在使用 LinearLayoutManager

时恢复位置

请帮帮我 提前致谢

问题描述不清楚。我还在努力回答。

假设您在点击列表时开始新的 Activity。根据 activity 的生命周期,背景 activity 将保持与滚动相同的状态。当你完成新的 activity 返回时 activity 将处于相同状态。

这可能是由于以下原因造成的

  1. 您正在使用 onResume 方法重新加载数据。你应该加载数据 onCreateView.
  2. 您正在从第 activity 秒开始后台 activity。

在 Activity 上使用 onPause 方法保存状态并在 onResume() 方法上恢复它 见代码

 public class Activity extends AppCompatActivity
 {
    private final String STATE = "recycler_state";
    private RecyclerView mRecyclerView;
    private static Bundle mBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);//set to whatever view id you use
        // don't forget to set your adapter
    }

    @Override
    protected void onPause()
    {
        super.onPause();

        // save RecyclerView state

        mBundle = new Bundle();
        Parcelable listState = mRecyclerView.getLayoutManager().onSaveInstanceState();
        mBundle.putParcelable(STATE, listState);
    }

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

        // restore RecyclerView state
        if (mBundle != null) {
            Parcelable listState = mBundle.getParcelable(STATE);
            mRecyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
}

我不是很清楚你的问题。我假设你当前的 activity 在你进入下一个细节时被破坏,因此当你返回时重新创建 activity 。转到下一个详细信息时不要调用 finish,只需调用 onBackPressed 返回上一个 activity。这将维护您的 recyclerView 状态和位置。

无论如何,您可以使用 Shared Preferences 保存位置,然后转到下一个细节并在 onResume 上取回。

你可以使用这个技巧:

int firstItemPos = mLayoutManager.findFirstVisibleItemPosition();
View v = mLayoutManager.findViewByPosition(firstItemPos);
int offsetPixel = 0;
if(v != null) offsetPixel = v.getTop();

然后当你恢复位置时:

mLayoutManager.scrollToPositionWithOffset(firstItemPos, offsetPixel)

firstItemPos 和 offsetPixel 可以保存在 activity 的额外捆绑包中。 mLayoutManager 在我的示例中我使用普通的 LinearLayoutManager 并将其设置为我的 Recycle View:

mLayoutManager = new LinearLayoutManager(getActivity())