无尽的滚动列表视图无法正常工作

我正在开发一个应用程序。 在我的应用程序中,我使用listview来显示来自json的数据。 所有数据都完美显示。 但我想要的是,显示前10个对象,然后加载项目应显示,然后剩余10将显示。 我的json响应如下所示。

{ "interestsent": [ { "interestsent_user_id":369, "name":"abc", "profile_id":"686317", "image":"", }, { "interestsent_user_id":369, "name":"def", "profile_id":"686318", "image":"", }, { "interestsent_user_id":369, "name":"ghi", "profile_id":"686319", "image":"", }, { "interestsent_user_id":369, "name":"jkl", "profile_id":"686320", "image":"", }, { "interestsent_user_id":369, "name":"mno", "profile_id":"686321", "image":"", }, { "interestsent_user_id":369, "name":"pqr", "profile_id":"686322", "image":"", }, ................. ................. ] } 

Interestsent.java

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); INTEREST_SENT_URL = "http://fshdfh.com/webservice/interestsent?version=apps&user_login_id=00"; new GetData().execute(""); listview = (ListView) findViewById(R.id.listview); Log.i("DATA", "page ::onCreate onCreate onCreate "); mHandler = new Handler(); listview.setOnScrollListener(new EndlessScrollListener() { @Override public void onLoadMore(int page, int totalItemsCount) { Log.i("DATA", "page :: " + page + " totalItemsCount :: " + totalItemsCount); mProgressbar = new ProgressDialog(MainActivity.this); mProgressbar.setMessage("Loading..."); mProgressbar.show(); count++; if (count < maindata.size()) { if (adapter != null) { if (!isLoadingMore) { isLoadingMore = true; mHandler.postDelayed(loadMoreRunnable, 1000); } } } } }); } Runnable loadMoreRunnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (count < maindata.size()) { if (adapter != null) { adapter.addAll(maindata.get(count)); mHandler.removeCallbacks(loadMoreRunnable); isLoadingMore = false; if (mProgressbar.isShowing()) mProgressbar.dismiss(); } } } }; static  ArrayList<ArrayList> chunkList(List list, final int L) { ArrayList<ArrayList> parts = new ArrayList<ArrayList>(); final int N = list.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList(list.subList(i, Math.min(N, i + L)))); } return parts; } private ProgressDialog mProgressbar; public class GetData extends AsyncTask { ArrayList data = new ArrayList(); @Override protected void onPreExecute() { // TODO Auto-generated method stub mProgressbar = new ProgressDialog(MainActivity.this); mProgressbar.setMessage("Loading..."); mProgressbar.show(); super.onPreExecute(); } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub ArrayList<ArrayList> data = new ArrayList<ArrayList>(); ServiceHandler sh = new ServiceHandler(); /*try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ /*for (int i = 0; i  " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node interestsent = jsonObj.getJSONArray(INTEREST_SENT); // looping through All Contacts for (int i = 0; i < interestsent.length(); i++) { JSONObject c = interestsent.getJSONObject(i); // creating new HashMap // HashMap<ArrayList map = new HashMap(); HashMap map = new HashMap(); // adding each child node to HashMap key => value map.put(INTEREST_USER_ID, c.getString(INTEREST_USER_ID)); map.put(INTEREST_SENT_NAME,c.getString(INTEREST_SENT_NAME)); map.put(INTEREST_SENT_PROFILE, c.getString(INTEREST_SENT_PROFILE)); map.put(INTEREST_SENT_IMAGE, c.getString(INTEREST_SENT_IMAGE)); map.put(INTEREST_SENT_CAST, c.getString(INTEREST_SENT_CAST)); map.put(INTEREST_SENT_AGE, c.getString(INTEREST_SENT_AGE)+" years"); map.put(INTEREST_SENT_LOCATION, c.getString(INTEREST_SENT_LOCATION)); // adding HashList to ArrayList data.addAll(map); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return data; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); maindata = chunkList(data, 50); Log.i("DATA", "maindata :: " + maindata.size()); adapter = new CustomAdapterSent(maindata.get(count), MainActivity.this); listview.setAdapter(adapter); if (mProgressbar.isShowing()) mProgressbar.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } 

EndlessScroolListener.java

  public abstract class EndlessScrollListener implements OnScrollListener { // The minimum amount of items to have below your current scroll position // before loading more. private int visibleThreshold = 5; // The current offset index of data you have loaded private int currentPage = 0; // The total number of items in the dataset after the last load private int previousTotalItemCount = 0; // True if we are still waiting for the last set of data to load. private boolean loading = true; // Sets the starting page index private int startingPageIndex = 0; public EndlessScrollListener() { } public EndlessScrollListener(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } public EndlessScrollListener(int visibleThreshold, int startPage) { this.visibleThreshold = visibleThreshold; this.startingPageIndex = startPage; this.currentPage = startPage; } // This happens many times a second during a scroll, so be wary of the code you place here. // We are given a few useful parameters to help us work out if we need to load some more data, // but first we check if we are waiting for the previous load to finish. @Override public void onScroll(AbsListView view,int firstVisibleItem,int visibleItemCount,int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount  previousTotalItemCount)) { loading = false; previousTotalItemCount = totalItemCount; currentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!loading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) { onLoadMore(currentPage + 1, totalItemCount); loading = true; } } // Defines the process for actually loading more data based on page public abstract void onLoadMore(int page, int totalItemsCount); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Don't take any action on changed } } 

CustomAdapterSent.java

公共类CustomAdapterSent扩展BaseAdapter {

 private ArrayList mData = new ArrayList(); private Context mContext; private LayoutInflater inflater = null; private static final String TAG_NAME="name"; private static final String TAG_PROFILE="profile_id"; private static final String TAG_IMAGE="image"; private static final String TAG_CAST="cast"; private static final String TAG_AGE="age"; private static final String TAG_LOCATION="location"; public CustomAdapterSent(ArrayList mData, Context mContext) { this.mContext = mContext; this.mData = mData; inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void addAll(ArrayList mmData) { this.mData.addAll(mmData); this.notifyDataSetChanged(); } @Override public int getCount() { // TODO Auto-generated method stub return mData.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return mData.get(arg0); } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } class ViewHolder { public TextView txtView; TextView txtproname; } @Override public View getView(int postion, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = convertView; ViewHolder holder; if (view == null) { view = inflater.inflate(R.layout.row_layout, null); holder = new ViewHolder(); ///holder.propic = (ImageView) convertView.findViewById(R.id.propicsent); // holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameintsent); //holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidsent); //holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastintsent); //holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageintsent); // holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceintsent); holder.txtView = (TextView) view.findViewById(R.id.no_intsent); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } Log.i("DATA", "mData.get(postion) :: " + mData.get(postion)); mData.get(postion); // holder.txtproname.setText(listData.get(position).get(TAG_NAME)); holder.txtView.setText("Index :: " + Integer.getInteger(TAG_NAME)); return view; } } 

XML文件:

      

要在ListView首次仅显示10个项目并在滚动时显示更多项目,请按照以下步骤操作:

步骤1:创建一个chunkList方法,将ArrayList分成大小为10的部分:

 static  List> chunkList(List list, final int L) { List> parts = new ArrayList>(); final int N = list.size(); for (int i = 0; i < N; i += L) { parts.add(new ArrayList( list.subList(i, Math.min(N, i + L))) ); } return parts; } 

第2 ArrayList 创建ArrayList和显示当前部分的计数器:

  private boolean isLoadingMore=false; Handler mHandler = new Handler(); List>> mainArrayList; private int count=0; 

第3 onPostExecute onPostExecute中断result并在ListView中显示数据:

 protected void onPostExecute(ArrayList> result) { super.onPostExecute(result); // your code here... mainArrayList=chunkList(result,10); isLoadingMore=false; count=0; adapter = new CustomAdapterSent(Interestsent.this, mainArrayList.get(count)); setListAdapter(adapter); } } 

步骤4:在Adapter中创建addAll方法以在当前数据源中附加数据:

 public void addAll(ArrayList> moreData){ this.listData.addAll(moreData); this.notifyDataSetChanged(); } 

第5 onLoadMore onLoadMore加载ListView中的更多数据:

 mHandler = new Handler(); listview.setOnScrollListener(new EndlessScrollListener() { @Override public void onLoadMore(int page, int totalItemsCount) { if(count 

要有一个AdapterView(例如ListView或GridView),当用户滚动项目(也就是无限滚动)时会自动加载更多项目。 这是通过在用户超过剩余项目的阈值之前触发对更多数据的请求来完成的。 每个AdapterView都支持绑定到OnScrollListener事件,只要用户滚动集合就会触发这些事件。 使用这个系统,我们可以通过创建扩展OnScrollListener的自己的类来定义一个基本的EndlessScrollListener,它支持大多数用例。

您可以在以下链接中找到更多相关信息:

Android中无尽的滚动ListView

使用AdapterViews无限滚动

无限滚动列表视图

在这个SO答案中展示了一种在listview中添加数据的简单方法: Android Endless List

希望这可以帮助 …