2014-01-09 112 views
4

在MainActivity中,我創建了DownloadTask,它填充模型類,然後通過CustomListAdapter類實現listview,但是我創建了識別滾動結束的函數,並且希望將更多項加載到列表視圖。我正在閱讀並在互聯網上查看代碼,但我無法解決這個問題,因爲它有點不同。 MainActivity類別ListView在滾動底部加載更多

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(); 
     } 
    } 

CustomListAdapter

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 
    { 
     //// 
    } 


} 

當我到創建敬酒底部。

回答

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方法,它就可以爲你解決問題。

+0

你能給我的例子嗎?我是Android新手,所以我不知道最好的方法 –

+0

我編輯了我的答案並添加了一個樣本/僞代碼。如果不夠清楚,請告訴我。 – ayorhan

+0

但我如何添加NewData?正如你所看到的,我通過private int mCount = 25限制了這些項目;在適配器 –

1
 @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(); 
        } 
      } 

     } 
+0

私人LinearLayoutManager mLayoutManager; \t private int previousTotal = 0; \t private boolean loading = true; \t private int visibleThreshold = 5; \t int firstVisibleItem,visibleItemCount,totalItemCount; –

相關問題