android:layout_weight="1"這一句可以使中間的textview權重增大,從而後面的checkbok可以居右顯示。
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
這三句很重要,如果不加就會出現錯誤。巴黎希爾頓芭蕾海濱髮型
由於checkbox的點擊事件優先順序比listview的高,所以要在checkbox中添加android:focusable="false",使得checkbox初始的時候沒有擷取焦點。
接下來在main.xml中添加Listview組件
package com.zwq.umeng;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Map<String, Object>> mData;
public static Map<Integer, Boolean> isSelected;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
init();
}
//初始化
private void init() {
mData=new ArrayList<Map<String, Object>>();
for (int i = 0; i < 5; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("img", R.drawable.icon);
map.put("title", "第" + (i + 1) + "行的標題");
mData.add(map);
}
//這兒定義isSelected這個map是記錄每個listitem的狀態,初始狀態全部為false。
isSelected = new HashMap<Integer, Boolean>();
for (int i = 0; i < mData.size(); i++) {
isSelected.put(i, false);
}
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//convertView為null的時候初始化convertView。
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.vlist, null);
holder.img = (ImageView) convertView.findViewById(R.id.img);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.cBox = (CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.img.setBackgroundResource((Integer) mData.get(position).get(
"img"));
holder.title.setText(mData.get(position).get("title").toString());
holder.cBox.setChecked(isSelected.get(position));
return convertView;
}
public final class ViewHolder {
public ImageView img;
public TextView title;
public CheckBox cBox;
}
}