【问题标题】:Maintain the scroll position of a listview after getting new data获取新数据后保持listview的滚动位置
【发布时间】:2016-05-25 20:53:45
【问题描述】:

我有一个列表视图,在刷新它并获取新数据后。它转到列表视图的顶部,而不是我上次滚动到的位置。

我设置了一个计时器,它会在 2 秒后获取新数据并将其放入列表视图中。

任何帮助将不胜感激。在此先感谢:D

这里是主要活动

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

    listView = (ListView) findViewById(R.id.listView);
    listView.setOnItemClickListener(this);

    getJSON();

    handler.postDelayed(runnable, 3500);
} 

 private Runnable runnable = new Runnable() {
    @Override
    public void run() {

        getJSON();

        handler.postDelayed(this, 2000);
    }
};

private void showEmployee(){
    JSONObject jsonObject = null;
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
    try {
        jsonObject = new JSONObject(JSON_STRING);
        JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);

        for(int i = 0; i<result.length(); i++){
            JSONObject jo = result.getJSONObject(i);
            String id = jo.getString(Config.TAG_ID);
            String name = jo.getString(Config.TAG_NAME);

            HashMap<String,String> employees = new HashMap<>();
            employees.put(Config.TAG_ID,id);
            employees.put(Config.TAG_NAME,name);
            list.add(employees);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(
            MainActivity.this, list, R.layout.list_item,
            new String[]{Config.TAG_ID,Config.TAG_NAME},
            new int[]{R.id.id, R.id.name});

    listView.setAdapter(adapter);

}

 private void getJSON(){
    class GetJSON extends AsyncTask<Void,Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            JSON_STRING = s;
            showEmployee();
        }
        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(Config.URL_GET_ALL);
            return s;
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute();
}

【问题讨论】:

  • 只是通知适配器进行更改。
  • 查看更多关于 listview 属性中的 transcriptMode 的信息
  • 为什么要投票?原因

标签: android listview


【解决方案1】:

在 onCreate() 中使用空列表初始化适配器并与 listView 绑定。 使您的适配器和列表在课堂上全局化。

现在每当您向适配器添加数据时,只需调用 adapter.notifyDataSetChanged()

这也是它在片段中的工作方式。

【讨论】:

    【解决方案2】:

    ListView 滚动到顶部,因为再次设置了 Adapter。无需在每次收到新数据时都设置Adapter,您只需将新数据添加到已经存在的List/dataset 并在ListView 的Adapter 上调用notifyDatasetChanged()。 ListView 的位置不会改变。

    【讨论】:

      【解决方案3】:

      要恢复滚动位置,请使用这个。

          Parcelable state;
      
           @Override
         public void onPause() {    
        // Save ListView state @ onPause
        Log.d(TAG, "saving listview state @ onPause");
         state = listView.onSaveInstanceState();
        super.onPause();
      }
      

      ...

      @Override
      public void onViewCreated(final View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      // Set new items
       listView.setAdapter(adapter);
      ...
       // Restore previous state (including selected item index and scroll        position)
       if(state != null) {
          Log.d(TAG, "trying to restore listview state..");
          listView.onRestoreInstanceState(state);
      }
      

      }

      【讨论】:

        【解决方案4】:

        在您的列表视图的 onScrollListner 中尝试此操作,获取最后一个可见项目的位置,当您加载更多数据时,设置列表视图的 setSelection

        int ScrollPos=0;
        
        listview.setOnScrollListener(new OnScrollListener() {
        
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                    int threshold = 1;
                    int count = listview.getCount();
                    if (listViewList1.size() >= YOUR LOAD ELEMENTS SIZE(Everytime))
                        if (scrollState == SCROLL_STATE_IDLE) {
                            if (listview.getLastVisiblePosition() >= count
                                    - threshold) {
                                scrollPos = listViewList.size();
                                // Execute LoadMoreDataTask AsyncTask
        
                            }
                        }
                }
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {
                    // TODO Auto-generated method stub
                }
            });
        

        在再次获取更多数据时,只需调用 Listview.setSelection(scrollPos) 并且第一次设法将你的滚动位置设置回 0 希望对你有帮助

        【讨论】:

          【解决方案5】:

          您必须将适配器和列表声明为实例变量,而不是在本地声明它们。每当数据发生变化时,必须对列表进行相关更新操作,然后调用适配器的 notifyDataSetChanged() 方法更新列表视图。

          将您的代码更改为:

          ArrayList<HashMap<String,String>> list;
          ListAdapter adapter;
          
          @Override
          protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          
          listView = (ListView) findViewById(R.id.listView);
          list = new ArrayList<HashMap<String, String>>();//changed
          adapter = new SimpleAdapter(
              MainActivity.this, list, R.layout.list_item,
              new String[]{Config.TAG_ID,Config.TAG_NAME},
              new int[]{R.id.id, R.id.name});//changed
          
          listView.setAdapter(adapter);
          listView.setOnItemClickListener(this);
          
          getJSON();
          
          handler.postDelayed(runnable, 3500);
          } 
          
          private Runnable runnable = new Runnable() {
          @Override
          public void run() {
          
              getJSON();
          
              handler.postDelayed(this, 2000);
          }
          };
          
          private void showEmployee(){
          JSONObject jsonObject = null;
          ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
          try {
              jsonObject = new JSONObject(JSON_STRING);
              JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
          
              for(int i = 0; i<result.length(); i++){
                  JSONObject jo = result.getJSONObject(i);
                  String id = jo.getString(Config.TAG_ID);
                  String name = jo.getString(Config.TAG_NAME);
          
                  HashMap<String,String> employees = new HashMap<>();
                  employees.put(Config.TAG_ID,id);
                  employees.put(Config.TAG_NAME,name);
                  list.add(employees);
              }
          
          } catch (JSONException e) {
              e.printStackTrace();
          }
          
          adapter.notifyDataSetChanged();//changed
          
          }
          
          private void getJSON(){
          class GetJSON extends AsyncTask<Void,Void,String> {
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
              }
          
              @Override
              protected void onPostExecute(String s) {
                  super.onPostExecute(s);
                  JSON_STRING = s;
                  showEmployee();
              }
              @Override
              protected String doInBackground(Void... params) {
                  RequestHandler rh = new RequestHandler();
                  String s = rh.sendGetRequest(Config.URL_GET_ALL);
                  return s;
              }
          }
          GetJSON gj = new GetJSON();
          gj.execute();
          }
          

          【讨论】:

            猜你喜欢
            • 2012-03-04
            • 2012-10-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-04-23
            • 2011-03-02
            • 1970-01-01
            相关资源
            最近更新 更多