package com.zxl.zhihu; import java.util.HashMap; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class ListViewAdapter extends BaseAdapter { private List<HashMap<String, Object>> list; private LayoutInflater listContainer; public ListViewAdapter(Context context, List<HashMap<String, Object>> list) { this.list = list; listContainer = LayoutInflater.from(context); } final class ListItemView { public ImageView image; public TextView text; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } //key code @Override public View getView(int position, View convertView, ViewGroup parent) { //重寫該函數,使每一個ListView Item根據自定義顯示 ListItemView itemView = null; if (convertView == null) { itemView = new ListItemView(); convertView = listContainer.inflate(R.layout.listview, null); itemView.image = (ImageView)convertView.findViewById(R.id.id_listView_image); itemView.text = (TextView) convertView.findViewById(R.id.id_listView_text); convertView.setTag(itemView); } else { itemView = (ListItemView)convertView.getTag(); } HashMap<String, Object> hashMap = list.get(position); Integer id = (Integer)hashMap.get("image"); String text = (String)hashMap.get("text"); itemView.image.setBackgroundResource(id); itemView.text.setText(text); return convertView; } }
實現簡單的自定義ListView
java