我是android编程的noobie,我正在使用Android studio,我有一个包含两个textview和一个复选框的listview项目。 我正在尝试使用复选框创建一个listiview,因此当单击特定按钮时,我将获得一个列表,其中包含已选中项目的名称。 尝试寻找教程和其他有用的东西,但只是无法做到正确。 谢谢大家 :) 这是我对listview的自定义适配器:
public class postadapter extends ArrayAdapter<post> {
ArrayList<post> list = new ArrayList<post>();
Context context;
int layoutResourceId;
post data[] = null;
public postadapter(Context context, int layoutResourceId, ArrayList<post> list) {
super(context, layoutResourceId, list);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.list = list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
holder.txtdescription = (TextView) row.findViewById(R.id.textView2);
holder.chk = (CheckBox) row.findViewById(R.id.chkbox);
row.setTag(holder);
holder.chk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
post post1 = (post) cb.getTag();
post1.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder)row.getTag();
}
post post1 = list.get(position);
holder.txtTitle.setText(post1.getPostname());
holder.txtdescription.setText("מספר שומרים:"+post1.getnumberguards()+" משעה: "+post1.getstime()+" עד שעה: "+post1.getetime());
holder.chk.setChecked(post1.isSelected());
return row;
}
static class ViewHolder
{
TextView txtTitle;
TextView txtdescription;
CheckBox chk;
}
}
答案 0 :(得分:3)
您可以维护所有选中复选框的布尔数组 -
boolean[] checkBoxState
checkBoxState= new boolean[list.size()]
然后在getView方法中使用此数组 -
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if(((CheckBox)v).isChecked())
{
checkBoxState[position]=true;
}
else
{
checkBoxState[position]=false;
}
}
});
从此数组中检索位置(此处适配器是自定义适配器的对象) -
for(int k = 0; k&lt; adapter.checkBoxState.length; k ++) {
如果(adapter.checkBoxState [K] == TRUE) { }`