2014-01-09 2 views
4

MainActivity에서 모델 클래스를 채우고 CustomListAdapter 클래스를 통해 listview를 생성하는 DownloadTask를 만들지 만 스크롤의 끝을 인식하는 함수를 만들었고 목록 뷰에 더 많은 항목을로드하려고합니다. 나는 인터넷에서 코드를 읽고보고 있었지만, 종류가 다르기 때문에이 문제를 해결할 수 없다. MainActivity 클래스ListView load below scroll bottom

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

을 그리고 당신은 당신의 목록보기를 업데이트 할 때 당신이 당신의 업데이트 방법에 그랬던 것처럼, 새로운 어댑터를 작성하지 않습니다 :

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 
} 

는 그리고 당신은 또한 다음과 같은 방법을 업데이트해야합니다. 그렇게하면 이전 콘텐츠가 삭제됩니다. 대신 어댑터의 addMoreItems 메서드를 호출하면 트릭이 수행됩니다.

+0

당신은 나에게 예를 들어 주실 수 있습니까? 나는 그렇게 할 수있는 가장 좋은 방법을 모른다. 안드로이드가 처음이다. –

+0

나는 내 대답을 편집하고 샘플/의사 코드를 추가했다. 충분히 명확하지 않으면 알려주십시오. – ayorhan

+0

하지만 어떻게 NewData를 추가 할 수 있습니까? 당신이 보았 듯이 private int mCount = 25; in adapter –

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

private LinearLayoutManager mLayoutManager; \t private int previousTotal = 0; \t private 부울로드 = true; \t private int visibleThreshold = 5; \t int firstVisibleItem, visibleItemCount, totalItemCount; –