如何遍历并获取listview中checkbox是否选中以及该项的id?
这是我之前解决这个问题写的东西,直接贴上来,你看下吧。
private List<Boolean> originalFoundedDevicesState; //有一个保存状态的list
给listview绑定adapter:
private CheckAdapter foundedDevices;
private ListView foundedList;
foundedDevices=new CheckAdapter(AddingDevicesAct.this,originalFoundedDevices,originalFoundedDevicesState);
foundedList.setAdapter(foundedDevices);
foundedList.setItemsCanFocus(false); foundedList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
foundedList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
} });
2.自己为checkbox复写个adapter:
class CheckAdapter extends BaseAdapter{
Context mContext;
List<Device> mData;
List<Boolean>status;
LayoutInflater mInflater;
CheckBox checkBox;
HashMap<Integer,View> lmap=new HashMap<Integer,View>();
public CheckAdapter(Context context,List<Device> data,List<Boolean> DeviceStatus)
{
mInflater=LayoutInflater.from(context);
mData=data;
status=DeviceStatus;
}
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mData.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(lmap.get(position)==null)
{
convertView=mInflater.inflate(R.layout.child,parent, false);
checkBox=(CheckBox)convertView.findViewById(R.id.devices);
convertView.setTag(checkBox);
}
else
{
checkBox=(CheckBox)convertView.getTag();
}
checkBox.setId(position);
checkBox.setChecked(status.get(position));
checkBox.setText(mData.get(position).toString());
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
status.set(buttonView.getId(), isChecked);
notifyDataSetChanged();
}
});
return convertView;
}
3.最后可以根据其是否被选中状态判断某项是否被选中,并提取id:
for(num1=0;num1<originalFoundedDevicesState.size();num1++)
{
if(originalFoundedDevicesState.get(num1))
finalPairedDevices.add(new Device(originalFoundedDevices.get(num1).getName(), originalFoundedDevices.get(num1).getAddress()));
}
private PromotionManageTo promotionManageTo;
private List<PromotionManageTo> productClass;
get…
set…
JSP里面:
<s:iterator value="productClass" status="productClassLength">
<td>
<input type="checkbox" name="promotionManageTo.productId" value="<fs:property value="productId"/>" <c:if test="${fn:containsIgnoreCase(promotionManageTo.productId, productId)}">checked="checked"</c:if> />
</td>
</s:iterator>
里,每次选中或取消的时候记录当前位置存放到map中,每次getview的时候去查map当前位置是否被选中的。