Listview is working incorrectly with implementing a load more function

若如初见. 提交于 2019-12-11 15:39:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!