Each item of my listview contains a checkbox.
I want the checkbox to be checked/unchecked whenever i click on a row of my listview. Now, the checkbox and the listview item are two separated things, which means i can click on the listview item ("behind" the checkbox) or on the checkbox.
The problem is that if i click on the checkbox, it doesn't trigger the itemClickListener (which is logical since they are separated).
So what i want is for the items and checkboxes to work "as one".
Here are the relevant parts of my code:
Activity:
listView.setAdapter(new FoodTypeAdapter(this, foodTypeList));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = (CheckBox) view.findViewById(R.id.foodType);
if (cb.isChecked()) {
intent.putExtra("position", position);
}
}
});
Adapter:
private boolean[] checkBoxState;
public FoodTypeAdapter(Context context, List<FoodType> foodTypeList) {
this.foodTypeList = foodTypeList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checkBoxState = new boolean[foodTypeList.size()];
}
static class ViewHolder {
protected CheckBox foodType;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View newView;
if (convertView == null) {
newView = inflater.inflate(R.layout.food_type_row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.foodType = (CheckBox) newView.findViewById(R.id.foodType);
newView.setTag(viewHolder);
} else {
newView = convertView;
}
final ViewHolder holder = (ViewHolder) newView.getTag();
holder.foodType.setText(foodTypeList.get(position).getName());
holder.foodType.setChecked(checkBoxState[position]);
holder.foodType.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return newView;
}
Listview row:
<CheckBox
android:id="@+id/foodType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false"
android:text="Checkbox"
android:textSize="16sp"/>
I know alot of topics about this already exist but i haven't found one with the same issue...
Help me please!
Aucun commentaire:
Enregistrer un commentaire