【ListView】滚动且加载数据

public class ListBaseAdapter extends BaseAdapter {

    

    private Context context;

    private ArrayList<String> list;

    public int count = 30;

    

    public ListBaseAdapter (Context context, ArrayList<String> list ) {

        this.context = context;

        this.list = list;

         

    }

    @Override

    public int getCount() {

        return count;

    }

    @Override

    public Object getItem(int item) {

        return item;

    }

    @Override

    public long getItemId(int id) {

        return id;

    }

    @Override

    public View getView(int arg0, View view, ViewGroup arg2) {

        ViewHolder viewHolder;

        if (view == null) {

            viewHolder = new ViewHolder();

            view = View.inflate(context, R.layout.activity_main_item, null);

            viewHolder.tv = (TextView) view.findViewById(R.id.tv_01);

            view.setTag(viewHolder);

        } else {

            viewHolder = (ViewHolder) view.getTag();  

        }

        viewHolder.tv.setText(list.get(arg0)+"");

        return view;

    }

    private class ViewHolder{

        TextView tv;

    }



}
View Code

 

public class MainActivity extends Activity {

    

    private ListView lv;

    private ArrayList<String> list;

    private int lastitem = 0;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        lv = (ListView) this.findViewById(R.id.listview01);

        

        loadData(); 

        

        final ListBaseAdapter listAdapter = new ListBaseAdapter(MainActivity.this, list);

        lv.setAdapter(listAdapter);

        lv.setOnScrollListener(new OnScrollListener() {

            @Override

            public void onScroll(AbsListView view, int firstVisibleItem,

                    int visibleItemCount, int totalItemCount) {

                lastitem = totalItemCount;

                //Log.i("QQQ", "lastitem.111.." + lastitem);

            }

            @Override

            public void onScrollStateChanged(AbsListView view, int scrollState) {

                //Log.i("QQQ", "lastitem.222.." + lastitem);

                if (lastitem != 100) {

                    if (lastitem == listAdapter.count

                            && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {

                        listAdapter.count += 10;

                        listAdapter.notifyDataSetChanged();

                    }

                } else {

                    Toast.makeText(getApplicationContext(), "啦啦啦啦", 1).show();

                }

            }

        });

    }

    

    private void loadData() {

        list = new ArrayList<String>();

        for (int i=0; i<100; i++) {

            list.add("张三"+i);

        }

        

    }





}
View Code

 

你可能感兴趣的:(ListView)