单选功能 提供Adapter的 处理代码
实现的思路是 用一个 map 保存下刚才选择的position item, 在adapter里面 设置 选中状态的时候 从 map里面获取。再次点击选择其他position的item的时候,将map中上一次 保存的 position的item删掉,最后一次点击的position 在每次点击的时候用一个单独的变量保存。 在点击事件里面重新notify当前 adapter 。
代码语言:javascript复制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.CompoundButton;
import android.widget.TextView;
import com.ccvideo.R;
import com.yizhibo.video.bean.pay.OptionListEntity;
public class ExchangeCoinsAdapter extends BaseAdapter {
private Context context;
private List<OptionListEntity> mList;
private Map<Integer, Boolean> isCheckMap = new HashMap<Integer, Boolean>();
private int lastPosition;
private int checkedRmb;
public ExchangeCoinsAdapter(Context context) {
this.context = context;
mList = new ArrayList<OptionListEntity>();
}
public void setData(List<OptionListEntity> list) {
mList = list;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.item_exchange_coins, viewGroup, false);
viewHolder = new ViewHolder();
viewHolder.exchangeCoinsTv = (TextView) view.findViewById(R.id.exchange_coins_tv);
viewHolder.exchangeGiveCoinsTv = (TextView) view.findViewById(R.id.exchange_coins_give_tv);
viewHolder.exchangeMoneyCb = (CheckBox) view.findViewById(R.id.exchange_money_tv);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final OptionListEntity model = mList.get(i);
viewHolder.exchangeCoinsTv.setText(context.getString(R.string.e_coin_count_rear, model.getEcoin()));
viewHolder.exchangeGiveCoinsTv
.setText(context.getString(R.string.e_coin_give_count_rear, model.getFree()));
viewHolder.exchangeMoneyCb
.setText(context.getString(R.string.cash_count_simple, model.getRmb() / 100));
viewHolder.exchangeMoneyCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (isCheckMap.size() > 0) {
isCheckMap.remove(lastPosition);
}
checkedRmb = model.getRmb();
isCheckMap.put(i, true);
lastPosition = i;
ExchangeCoinsAdapter.this.notifyDataSetChanged();
}
});
if (isCheckMap != null && isCheckMap.containsKey(i)) {
viewHolder.exchangeMoneyCb.setSelected(isCheckMap.get(i));
} else {
viewHolder.exchangeMoneyCb.setSelected(false);
}
return view;
}
public int getCheckedRmb() {
return checkedRmb;
}
protected static class ViewHolder {
TextView exchangeCoinsTv;
TextView exchangeGiveCoinsTv;
CheckBox exchangeMoneyCb;
}
}