import java.util.HashMap; 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.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; public class LanguageAdapter extends BaseAdapter { private Context mContext; private String[] mListArrays; private LayoutInflater mInflater; //用於存儲CheckBox選中狀態 public Map<Integer,Boolean> mCBFlag = null; public LanguageAdapter(Context c,String[] arrays){ this.mContext = c; this.mListArrays = arrays; mInflater = LayoutInflater.from(mContext); mCBFlag = new HashMap<Integer, Boolean>(); init(); } //初始化CheckBox狀態 void init(){ for (int i = 0; i < mListArrays.length; i++) { mCBFlag.put(i, false); } } @Override public int getCount() { return mListArrays.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.item_layout_ui, null); holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.cb_item); holder.mTextView = (TextView) convertView.findViewById(R.id.tv_item); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } //狀態保存 holder.mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ mCBFlag.put(position, true); }else{ mCBFlag.put(position, false); } } }); /*CheckBox監聽事件必須放在setChecked以前,不然後果自負*/ holder.mCheckBox.setChecked(mCBFlag.get(position)); holder.mTextView.setText(mListArrays[position]); return convertView; } public final class ViewHolder{ public CheckBox mCheckBox; public TextView mTextView; } }