问题
So, I have a listview and getting the data for it from an external database. I would like to have 20 items the first time, then if the user scrolls down it loads another 20 and so on.
class ItemAdapter extends BaseAdapter {
private ArrayList<Item> objects;
private class ViewHolder {
public TextView text_tt;
}
@Override
public int getCount() {
return SIZE;
//return 9;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder viewHolder;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.text_tt = (TextView) v.findViewById(R.id.toptext);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if(position==getCount()-1){
LoadMore(); //asynctask - load other 20
}
return v;
}
}
In the load function I parse the pre-read json data so i just have to add another 20 one to the list and notifyDataSetChanged()
.. The function works well but it has a side effect: about 50% of the time the click on items is not recognized. I scroll down, receive the next 20 but I cannot click on any items. But for example if I change activity and come back to the listview, it works. Why?
Thank you!
回答1:
You can set a OnScrollListener
on your ListView
. In the onScroll()
method, check if:
firstVisible + visibleItemCount = totalItemCount
If this condition is satisfied, you can load more items from the database, reinitialize the adapter with the updated list of items.
listView.setOnScrollListener(new 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) {
// add 20 more items to the list and reinitialize the adapter
}
}
});
}
来源:https://stackoverflow.com/questions/17914291/listview-is-working-incorrectly-with-implementing-a-load-more-function