【问题标题】:How can i save the scroll position in a recycler view after every time i recreate it?每次重新创建滚动位置后,如何将滚动位置保存在回收站视图中?
【发布时间】:2021-06-06 23:42:12
【问题描述】:

以下是每次单击按钮时调用的方法,它会创建一个包含新数据的列表

public void fire(View v) {
    String temp = editText.getText().toString();

    myRecyclerView = new MyRecyclerView(this, 500, temp);
    recyclerView.setAdapter(myRecyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myRecyclerView.setClickListener(this);
} 

如何保存滚动位置,以便下次单击按钮时,列表保持在同一位置

【问题讨论】:

  • 为什么每次都创建一个新视图?这里的用例是什么?
  • 我正在制作一个应用程序,用户可以在其中输入任何文本并将其转换为不同的字体,这就是为什么我必须再次重新创建整个列表
  • 为此您不必每次都创建新视图。更改数据集就足够了。
  • 我该怎么做?

标签: java android android-recyclerview android-listview


【解决方案1】:

好吧,每次重新创建它时都使用它。

linearLayoutManager.scrollToPositionWithOffset(pos, 0);     

代码:

public void fire(View v) {
    String temp = editText.getText().toString();

    myRecyclerView = new MyRecyclerView(this, 500, temp);
    recyclerView.setAdapter(myRecyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
    myRecyclerView.setClickListener(this);
    //assuming th layout is loaded. set pos as the position you want to scroll to
    int pos=0;
    linearLayoutManager.scrollToPositionWithOffset(pos, 0); 

} 

【讨论】:

  • 谢谢你,我明白你的意思,但你能告诉我每次点击按钮时如何获取 pos 值吗?我尝试在适配器类中声明一个方法,我尝试调用 getAdapterPosition( )在其中,但我想我不能在那里使用这种方法,请问您有什么想法
  • 您可以使用回收视图适配器获取创建时的位置。
  • 谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 2019-05-26
  • 2019-04-27
  • 1970-01-01
相关资源
最近更新 更多