我正在尝试在列表视图内实现一个复选框。 listView是从JSON生成的。在适配器中,当我调用onCheckedChanged
时,我想要获取该复选框的ID,然后将其返回给服务器。如果我想使用自己的构造函数将ID设置为复选框,该怎么办?
public class CheckListAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener{
List List =new ArrayList();
SparseBooleanArray mCheckStates;
boolean[] itemChecked;
public CheckListAdapter(Context context, int resource) {
super(context, resource);
itemChecked = new boolean[10];
mCheckStates = new SparseBooleanArray(10);
}
public void add(@Nullable checkListItems object) {
super.add(object);
List.add(object);
}
@Override
public int getCount() {
return List.size();
}
@Nullable
@Override
public Object getItem(int position) {
return List.get(position);
}
public long getItemId(int position) {
return 0;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row;
row = convertView;
final checkListItemHolder h;
if ( row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_checklist,parent,false);
h = new checkListItemHolder();
h.tx_itemNo = (TextView) row.findViewById(R.id.checkListItemNO);
h.tx_name= (TextView) row.findViewById(R.id.checkListItemName);
h.checkBoxLab= (CheckBox) row.findViewById(R.id.checkBox);
row.setTag(h);
}
else
{
h = (checkListItemHolder)row.getTag();
}
checkListItems L= (checkListItems)this.getItem(position);
h.tx_name.setText(L.getItemName());
Log.w("inja to adaptor","ta inja");
h.tx_itemNo.setText(L.getItemNo());
// h.checkBoxLab.setChecked(false);
// h.checkBoxLab.setChecked(checkedHolder[position]);
h.checkBoxLab.setOnCheckedChangeListener( new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkedHolder[position] = isChecked;
Log.w("yahoo","yahoo");
}
});
return row;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
public boolean[] checkedHolder;
private void createCheckedHolder() {
checkedHolder = new boolean[getCount()];
}
static class checkListItemHolder{
TextView tx_name, tx_itemNo;
CheckBox checkBoxLab;
}
答案 0 :(得分:1)
将此行h.checkBoxLab.setTag(position)
添加到此行h.checkBoxLab= (CheckBox) row.findViewById(R.id.checkBox);
下
使用它从列表视图中删除行:
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Integer index = (Integer) buttonView.getTag();
List.remove(index.intValue());
notifyDataSetChanged();
}
,请解释您到底要返回服务器什么?
答案 1 :(得分:0)
您只需在onCheckedChanged方法内使用buttonView.getId()
即可获取复选框的ID。此视图始终引用Doc所述的复选框,其检查状态已更改。