Listview之优化BaseAdapter中的getView中的contentView

BaseAdapter中getView中改动的地方:

@Override
    public View getView(int position, View contentView, ViewGroup arg2) {
        TextView textview;
        ImageView imageView;
        //判断contentView是否为空,为空重新创建
        if(contentView == null){
            contentView =layoutInflater.inflate(R.layout.list_item, null);
             textview=(TextView)contentView.findViewById(R.id.textview);
             textview.setText((CharSequence) list.get(position).get("name"));
             imageView=(ImageView)contentView.findViewById(R.id.imageview);
             imageView.setImageResource((Integer) list.get(position).get("pictrue"));
        }else{
            //contentView不为空,返回已经存在的contentView
            return contentView;
        }
        


获取数据源中改动的地方:

MainActivity.java中的getData();

private List<Map<String, Object>> getData() {
        // TODO Auto-generated method stub

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "图1");
        map.put("pictrue", R.drawable.tu1);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("name", "图2");
        map.put("pictrue", R.drawable.tu2);
        list.add(map);
        
        
        map = new HashMap<String, Object>();
        map.put("name", "图3");
        map.put("pictrue", R.drawable.tu3);
        list.add(map);
        
        
        map = new HashMap<String, Object>();
        map.put("name", "图4");
        map.put("pictrue", R.drawable.tu4);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("name", "图5");
        map.put("pictrue", R.drawable.tu5);
        list.add(map);
        
        
        map = new HashMap<String, Object>();
        map.put("name", "图6");
        map.put("pictrue", R.drawable.tu6);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("name", "图7");
        map.put("pictrue", R.drawable.tu7);
        list.add(map);
        
        map = new HashMap<String, Object>();
        map.put("name", "图8");
        map.put("pictrue", R.drawable.tu8);
        list.add(map);
        
        return list;
    }
原文地址:https://www.cnblogs.com/childhooding/p/4325014.html