如何在listview中添加分页?

时间:2017-07-31 06:55:27

标签: java android listview pagination adapter

从下面的代码中,我成功地将数据添加到列表视图中。我想在列表视图中添加分页。我在每个请求中得到5个项目,当用户滚动到底部时,再次,我想调用一个Web服务并获得接下来的五个项目。另外,我想在从服务器获取数据时向底部添加一个加载器。我试过下面的代码,但失败了。我怎样才能做到这一点?

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ListView
                android:id="@+id/listview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="70dp"
                android:divider="@null" />

        </LinearLayout>

MainActivity.java

public void getTimeLineData(final String token, final String page) {
    timeLineItems = new ArrayList<TimeLineItem>();

    listAdapter = new TimeLineListAdapter(this, timeLineItems);
    listView.setAdapter(listAdapter);


    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
   /* getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    getActionBar().setIcon(
            new ColorDrawable(getResources().getColor(android.R.color.transparent)));*/

    // We first check for cached request

        String tag_string_req = "req_register";
        // making fresh volley request and getting json
        StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("status");
                        String message = jObj.getString("message");
                        if(error){
                            totalPages = jObj.getInt("totalPages");
                            pageCount = jObj.getInt("page");

                            int limit = jObj.getInt("limit");
                            parseJsonFeed(response);
                        }else {
                            Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
                        }

                    }catch (Exception e){

                    }

                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("my_token", token);
                params.put("page", page);
                params.put("limit", "5");

                return params;
            }
        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

private void parseJsonFeed(String response) {
    try {
        JSONObject jsonObj = new JSONObject(response);
        JSONArray feedArray = jsonObj.getJSONArray("data");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            TimeLineItem item = new TimeLineItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));
            item.setLname(feedObj.getString("lname"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("story_text"));
            item.setProfilePic(feedObj.getString("profile_pic"));
            item.setTimeStamp(feedObj.getString("time_stamp"));
            item.setIsLike(feedObj.getInt("is_like"));
            item.setTotalLikes(feedObj.getString("total_likes"));
            item.setTotalComment(feedObj.getString("total_comments"));

            /*// url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);*/

            timeLineItems.add(item);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    getTimeLineData(token , String.valueOf(requestCount));
    //Incrementing the request counter
    requestCount++;
}

public void timelineScrollItem(){

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(firstVisibleItem + visibleItemCount == totalItemCount){
                // End has been reached
                getData();
            }
        }
    });

}

2 个答案:

答案 0 :(得分:3)

用这个

替换setOnScrollListener
listView.setOnScrollListener(new OnScrollListener(){

   @Override
   public void onScrollStateChanged(AbsListView view, int scrollState) {}

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

   int lastInScreen = firstVisibleItem + visibleItemCount;    
   if((lastInScreen == totalItemCount) && !(loadingMore)){     
    getData();
   }
   }
  });

答案 1 :(得分:1)

您可以将此课程用于

rivate class CustomLoadingListItemCreator implements LoadingListItemCreator {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.custom_loading_list_item, parent, false);
    return new VH(view);
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // Bind custom loading row if needed
  }
}

您可以使用此library