如何遍历并获取listview中checkbox是否选中以及该项的id?

2025-01-03 00:03:41
推荐回答(3个)
回答(1):

这是我之前解决这个问题写的东西,直接贴上来,你看下吧。


      private List originalFoundedDevicesState; //有一个保存状态的list


  1. 给listview绑定adapter:


    private CheckAdapter foundedDevices;

    private ListView foundedList;


    foundedDevices=new CheckAdapter(AddingDevicesAct.this,originalFoundedDevices,originalFoundedDevicesState);


    foundedList.setAdapter(foundedDevices);

    foundedList.setItemsCanFocus(false);
  2. 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 mData;

Liststatus;

LayoutInflater mInflater;

CheckBox checkBox;

    HashMap lmap=new HashMap();

public CheckAdapter(Context context,List data,List 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

{

if(originalFoundedDevicesState.get(num1))

  finalPairedDevices.add(new Device(originalFoundedDevices.get(num1).getName(), originalFoundedDevices.get(num1).getAddress()));

}





回答(2):

Action里面:
private PromotionManageTo promotionManageTo;
private List productClass;
get…
set…
JSP里面:


" checked="checked" />

回答(3):

记录在map
里,每次选中或取消的时候记录当前位置存放到map中,每次getview的时候去查map当前位置是否被选中的。