android listview数据加载

2019-10-22 14:15:29 浏览数 (1)

大致思想

代码语言:javascript复制
private List<ZJLoction> searchListData = new ArrayList<ZJLoction>();
private ListView searchListView;
private AddressSearchAdapter searchAdapter;

如上面代码所示,定义了三个对象 searchListData数据源 searchListView数据显示的地方 searchAdapter连接数据源和展示的桥梁 可以这样比喻 searchListData货源 searchListView货仓 searchAdapter拉货的车 要建立之间的关系就要做如下操作

代码语言:javascript复制
searchListView = (ListView)findViewById(R.id.address_list_search);
searchAdapter = new AddressSearchAdapter(mAppContext);
searchListView.setAdapter(searchAdapter);

而要更新数据 也就是要通知拉货的车 代码如下

代码语言:javascript复制
searchAdapter.notifyDataSetChanged();

自定义Adapter

代码语言:javascript复制
private  class AddressSearchAdapter extends BaseAdapter {

    private final LayoutInflater mInflater;
    private final Context mContext;
    private AddressSearchAdapter(Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return searchListData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ZJLoction location = searchListData.get(position);
        AddressItem addressItem = null;
        if(convertView == null){
            convertView = mInflater.inflate(R.layout.address_item,null);
            addressItem = new AddressItem(convertView);
            convertView.setTag(addressItem);
        }else{
            addressItem =  (AddressItem)convertView.getTag();
        }
        addressItem.titleView.setText(location.getName());
        addressItem.detailView.setText(location.getAddress());
        return convertView;
    }
}

private  class AddressItem{

    TextView titleView;
    TextView detailView;
    public AddressItem(View convertView) {
        titleView = (TextView)convertView.findViewById(R.id.address_item_title);
        detailView = (TextView)convertView.findViewById(R.id.address_item_detail);
    }
}

通过判断convertView是否为空来复用

0 人点赞