I have a ListView with a custom adapter. The ListView will contain a list of checkboxes and each time a checkbox is clicked I want to add/remove the checkbox from an array inside my custom view, so I thought the best way to achieve this would be to use the onItemClickListener.
The thing is that this doesn't work, the code in the onItemClickListener never runs. I found many questions on SO about the same problem, but the solution that worked for them didn't work for me.
This is my code:
MultichoiceAnswerView.java
private void init(Context context) {
multichoiceAdapter = new MultichoiceAdapter(context, alternatives);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.view_answer_multichoice, this);
listAlternatives = (ListView) this.findViewById(R.id.list_alternatives);
listAlternatives.setAdapter(multichoiceAdapter);
// This is where I tried to add a onItemClickListener, with no success.
super.init();
}
MultichoiceAdapter.java
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
String alternative = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_multichoice, parent, false);
}
CheckBox checkBoxAlternative = (CheckBox) convertView.findViewById(R.id.checkBox_alternative);
checkBoxAlternative.setText(alternative);
return convertView;
}
view_answer_multichoice.xml
<ListView
android:id="@+id/list_alternatives"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:divider="@null"
android:dividerHeight="0dp" />
item_multichoice.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkBox_alternative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:text="Answer"/>
</LinearLayout>
The project can be accessed in this GitHub repo (branch "cards"): http://ift.tt/2fm55kJ
The solution I've tried: Setting focusable="false" on the checkbox. Setting focusableInTouchMode="false" on the checkbox (both with and without focusable="false") Setting descendantFocusability="blocksDescendants" to the LinearLayout Setting checkBoxAlternative.setFocusable(false); in the adapter (didn't try the other things though)
None of the above mentioned solutions worked. I did find a (obvious) way to fix this by setting clickable="false" on the checkbox, but if I can get this to work without having to programmatically check the box it would be great.
Maybe there is a clean workaround that I haven't thought of (maybe I could use a RecyclerView or something like that). So, how would I fix this? And why did the above mentioned solution not work for me?
Aucun commentaire:
Enregistrer un commentaire