【问题标题】:how to save data in a listView and scroll position while navigating between activities如何在活动之间导航时将数据保存在 listView 和滚动位置
【发布时间】:2014-01-15 23:07:45
【问题描述】:

我有一个扩展 ListActivityActivity ,在 onCreate 方法中我设置了 contentView 并调用 AsyncTask 来加载数据并且列表按我的意愿填充,问题是当我例如,检查详细活动并想要返回listView:我执行了onCreate 方法,再次加载数据,listView 滚动到顶部,失去了我之前的位置。 我想要实现的是类似于 google gmail 应用程序的东西,例如:列表视图被加载一次并保存滚动位置。

我在这里看了很多,我尝试了很多解决方案,但没有一个有效。

实现这种情况的最佳方法是什么?

我的活动:

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

    new LoadEvents().execute();
}

我的异步任务:

class LoadEvents extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Home.this);
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(AgendaIConstantes.URL_EVENTS, "GET", params);

                ......Processing 

                    eventList.add(map);
                }
            } else {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapterRes = getListAdapter();
                if(adapterRes == null){
                    ListAdapter adapter = new SimpleAdapter(Home.this, eventList,R.layout.list_item, 
                            new String[] { .....},
                            new int[] { .....});
                    setListAdapter(adapter);
                }
            }
        });

    }

【问题讨论】:

  • 你到底尝试了什么?在此处发布您的代码(相关部分)可能是值得的。当您回到仅暂停的Activity 时,不应执行 onCreate AFAIK,仅执行 onResume,因此您的 Activity 生命周期可能有问题。

标签: android android-listview android-activity savestate


【解决方案1】:

只是不要在每次调用onCreate 方法时执行加载任务。您可以在活动中使用布尔标志或使用onSaveInstanceState 保存状态。

顺便说一句,在onPostExecute 中调用getListAdapter 不是很好的方法,您的空值检查表明了这一点。

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2022-11-27
    • 1970-01-01
    • 2011-07-01
    • 2012-06-26
    • 1970-01-01
    相关资源
    最近更新 更多