【问题标题】:ListView load more on scroll bottomListView 在滚动底部加载更多
【发布时间】:2014-01-09 19:26:23
【问题描述】:

在 MainActivity 中,我创建了 DownloadTask,它填充模型类,然后通过 CustomListAdapter 类填充列表视图,但我创建了识别滚动结束的函数,并且我想将更多项目加载到列表视图中。我正在阅读和查看互联网上的代码,但我无法解决这个问题,因为它有点不同。 MainActivity 类

public void updateList() {
        adap = new CustomListAdapter(this, feedList, null);

         feedListView.setAdapter(adap);
         feedListView.setOnScrollListener(new OnScrollListener() {

             public void onScrollStateChanged(AbsListView view,
                     int scrollState) { // TODO Auto-generated method stub
                 int threshold = 1;
                 int count = feedListView.getCount();

                 if (scrollState == SCROLL_STATE_IDLE) {
                     if (feedListView.getLastVisiblePosition() >= count
                             - threshold) {
                         mHandler = new Handler();
                         mIsLoading = true;


               Toast.makeText(getApplicationContext(), "END",   Toast.LENGTH_LONG).show();
                     }
                 }
             }

             public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {


             }

         });


    }


     public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {

         @Override
         protected void onProgressUpdate(Integer... values) {
         }

         @Override
         protected void onPostExecute(Void result) {
                 if (null != feedList) {
                         updateList();
                 }

                 if (progressbar.isShown()) {
                  progressbar.setVisibility(View.INVISIBLE); 
                 }

         }

         @Override
         protected Void doInBackground(String... params) {
                 String url = params[0];

                 // getting JSON string from URL
                 JSONObject json = getJSONFromUrl(url);

                 //parsing json data
                 parseJson(json);
                 return null;
         }}
         public JSONObject getJSONFromUrl(String url) {
         InputStream is = null;
         JSONObject jObj = null;
         String json = null;

         // Making HTTP request
         try {
                 // defaultHttpClient
                 DefaultHttpClient httpClient = new DefaultHttpClient();
                 HttpPost httpPost = new HttpPost(url);

                 HttpResponse httpResponse = httpClient.execute(httpPost);
                 HttpEntity httpEntity = httpResponse.getEntity();
                 is = httpEntity.getContent();

                 BufferedReader reader = new BufferedReader(new InputStreamReader(
                                 is, "iso-8859-1"), 8);
                 StringBuilder sb = new StringBuilder();
                 String line = null;
                 while ((line = reader.readLine()) != null) {
                         sb.append(line + "\n");
                 }
                 is.close();
                 json = sb.toString();
         } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
         } catch (ClientProtocolException e) {
                 e.printStackTrace();
         } catch (IOException e) {
                 e.printStackTrace();
         }

         try {
                 jObj = new JSONObject(json);
         } catch (JSONException e) {
                 Log.e("JSON Parser", "Error parsing data " + e.toString());
         }

         // return JSON String
         return jObj;

   }

   public void parseJson(JSONObject json) {
         try {

                 // parsing json object
                 if (json.getString("status").equalsIgnoreCase("ok")) {
                         JSONArray posts = json.getJSONArray("posts");




                         feedList = new ArrayList<FeedItem>();

                         for (int i = 0; i < posts.length(); i++) {

                                 JSONObject post = (JSONObject) posts.getJSONObject(i);
                                 FeedItem item = new FeedItem();

                                /////.....  
                                 feedList.add(item); 



                         }

                         } 



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

自定义列表适配器

 public class CustomListAdapter extends BaseAdapter  
{



    private int mCount = 25;
    private ArrayList<FeedItem> listData;
    private LayoutInflater layoutInflater;
    private Context mContext;
    private ArrayList<String> data;
    protected ListView feedListView;

    public CustomListAdapter( Context context, ArrayList<FeedItem> listData)
    { 


        this.listData = listData;
        layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mContext = context;

    }

    public void addMoreItems(int count) {
        mCount += count;
        notifyDataSetChanged();
    }


    @Override
    public int getCount()
    {
        return mCount;
    }

    @Override
    public Object getItem(int position)
    {
        return position;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }


    public View getView( int position, View convertView, ViewGroup parent)
    {
     final ViewHolder holder;
     View row=convertView;
        if ((row == null) || (row.getTag()==null)) {

         convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
         holder = new ViewHolder();
      ////
         convertView.setTag(holder);






        }
        else
        {
            holder = (ViewHolder) convertView.getTag();

        }

       final FeedItem newsItem = (FeedItem) listData.get(position);
      /////



        return convertView;
    }


static class ViewHolder
    {
        ////
    }


}

当我到达底部时,吐司就创建好了。

【问题讨论】:

    标签: android listview load endlessadapter


    【解决方案1】:

    您可以将位置与列表数据大小进行比较,并在您的适配器类中相应地加载更多项目,而不是使用 OnScrollListener。

    public View getView( int position, View convertView, ViewGroup parent){
      if(position == getCount()-1){
         // load new items here. you can do a for loop here, if you'd like to add multiple items.
         addMoreItems(newItem);
      }
    
      // rest of the getView implementation
    }
    

    而且你还需要更新以下方法:

    public void addMoreItems(FeedItem newItem) {
       listData.add(newItem); // since you want to add this item at the end of the list
       notifyDataSetChanged();
    }
    
    @Override
    public int getCount(){
       return listData.size();
    }
    
    @Override
    public Object getItem(int position){
        return listData.get(position);
    }
    

    当你想更新你的 listView 时,不要创建一个新的适配器,就像你在更新方法中所做的那样。如果你这样做,它将摆脱以前的内容。相反,只需调用适配器的 addMoreItems 方法,它就会为您解决问题。

    【讨论】:

    • 你能给我举个例子吗?我是 Android 新手,所以我不知道最好的方法
    • 我编辑了答案并添加了示例/伪代码。如果还不够清楚,请告诉我。
    • 但是如何添加 NewData?如您所见,我将项目限制为 private int mCount = 25;在适配器中
    • 哦,我忽略了这一点,您不应该限制计数。您可以摆脱它并在 getCount() 方法中返回 listData.size()。
    • addMoreItems(newItem) 中的 newItem 该怎么办,因为 newItem 无法解析为变量
    【解决方案2】:
            @Override
            public void onScrollStateChanged(int scrollState) {
                // TODO Auto-generated method stub
    
                if(scrollState==RecyclerView.SCROLL_STATE_IDLE){
    
                      visibleItemCount = mLayoutManager.getChildCount();
                      totalItemCount = mLayoutManager.getItemCount();
                      firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
    
    
                      if (loading) {
                       if (totalItemCount > previousTotal) {
                        loading = false;
                        previousTotal = totalItemCount;
                       }
                      }
    
                      if (!loading  && (totalItemCount - visibleThreshold) <= (firstVisibleItem + visibleItemCount)) {
    
                          Log.v("scroll","Last Item Wow !");
    
                          if(footerView.getVisibility()!=View.VISIBLE){
                              footerView.setVisibility(View.VISIBLE);
                          }
    
                            refreshExpListViewData();
                      }
                }
    
            }
    

    【讨论】:

    • 私有 LinearLayoutManager mLayoutManager;私人int previousTotal = 0;私有布尔加载 = true;私有int可见阈值= 5; int firstVisibleItem, visibleItemCount, totalItemCount;
    【解决方案3】:

    实现“无限滚动”的一个非常简单的方法是使用 commonsguy 的 EndlessAdapter 库。

    https://github.com/commonsguy/cwac-endless

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2015-09-10
      • 1970-01-01
      • 2021-04-29
      • 2015-03-03
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多