【问题标题】:How can I maintain the position of listview when user comes back to the activity by pressing back button?当用户通过按返回按钮返回活动时,如何保持列表视图的位置?
【发布时间】:2016-06-04 09:07:01
【问题描述】:

我有一个listview,当我去另一个活动(通过启动另一个意图)然后回来(按后退按钮)时,如何保持我的ListView 在我的活动中的位置?当用户单击listview 中的任何项目时,另一个活动开始,并且在该活动中,当它按下前一个listview 活动时,我有一个后退按钮,活动恢复其状态并单击项目位置?我已经搜索过,但没有找到任何有用的东西,有没有办法在清单中做到这一点,因为我在listview 活动清单中使用了下面的代码来恢复其状态,我知道在方向更改后恢复状态不是一个好的选择,但在我的案例很有用。

android:configChanges="orientation|screenSize"

【问题讨论】:

  • 据我了解,当您打开新活动时,请确保您没有调用 finish();然后它应该保持你离开调用活动时的状态。如果你必须调用finish();然后在意图中传递 listview.getselecteditem() 的值;并在您重新创建原始活动时将其传回。
  • 不,我没有在 listview 活动中调用 finish()
  • 那么请在您的帖子中添加更多内容,展示您已经拥有的内容。

标签: android listview android-activity


【解决方案1】:

你可以,

  1. 使用 Intent.putExtra 将选定的索引传递给 SecondActivity,然后返回给 First。

  2. 使用 SharedPreferences 存储和检索索引。

如果你愿意,我可以详细说明。

【讨论】:

    【解决方案2】:
    int index = mList.getFirstVisiblePosition();
    View v = mList.getChildAt(0);
    int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
    

    top 为您提供可见的位置。然后可以保存在onSaveInstanceState()中(具体实现我不记得了)

    @Override
    public void onSaveInstanceState(Bundle bundle) {
         super.onSaveInstanceState(bundle);
         bundle.putInt("tag", top);
    }
    

    然后在 onCreate 中恢复你的位置并将其设置为列表

    mList.setSelectionFromTop(index, top);
    

    【讨论】:

      【解决方案3】:

      科特林方式

      val index: Int = recyclerView.scrollState
       
      recyclerView.scrollToPosition(index)
      

      【讨论】:

        猜你喜欢
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多