Reputation: 427
This is supposed to be something pretty straight forward but for some reason, the listener for the Checkbox does not work.
Here's my layout :
<RelativeLayout
android:layout_width="match_parent"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:layout_marginLeft="@dimen/dimen_5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:textStyle="bold"
android:text="@string/my_text"
/>
<CheckBox
android:id="@+id/check_status"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_height="wrap_content" />
</RelativeLayout>
And here's the implementation in my fragment:
CheckBox checkBox = mView.findViewById(R.id.check_status);
checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
LOGD(TAG, "IsButton checked ? "+ isChecked);
Toast.makeText(getActivity(), "Check",
Toast.LENGTH_SHORT).show();
}
});
Like I said, this is something supposed to be pretty straight forward, but the listener.....well it doesn't listen anything. I'm testing on Nexus 5x Oreo and a small Motorola Marshmallow.
At some point I even tried the setOnClickListener() method:
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LOGD(TAG, "IsButton checked ? "+ ((CheckBox)
v).isChecked());
}
});
The result is the same, I don't see anything in the logcat
Does anyone have a clue as to why the Checkbox's listener is not working properly ?
Upvotes: 0
Views: 4742
Reputation: 28865
If you use DataBinding
, set the attribute android:checked="@={viewModel.someState}"
and later call this listener via ViewBinding
like
binding.checkBox.setOnCheckedChangeListener { _, _ ->
//
}
setOnCheckedChangeListener
won't be called.
You can set app:checkListener
and use BindingAdapter
:
@BindingAdapter("app:checkListener")
fun CheckBox.setCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener) {
setOnCheckedChangeListener(listener)
}
Or observe changes in someState
:
viewModel.someState.observe(viewLifecycleOwner) {
viewModel.changeCheckBox()
// Other actions.
}
Upvotes: 4
Reputation: 5721
There are few reason to not works.
In your xml you have to at-lease define checked type as per your requirement.
android:checked="false"
In java file you have to required used setOnCheckedChangeListener()
.
Hope its work for all.
Upvotes: 1
Reputation: 5042
Most likely, setOnCheckedChangeListener()
is not being called :)
Upvotes: -2