Issue
I'm creating a form in android which asks for gender. To get this input I use Material Button Toggle Group which contains two buttons. I don't know how to know which button is clicked in my activity.java. How to get to know about the selected button in my activity so that i can save the details in different database.
myxml.xml
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:layout_marginStart="5dp"
style="?attr/materialButtonOutlinedStyle"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:layout_marginStart="10dp"
style="?attr/materialButtonOutlinedStyle"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
Myactivity.java
MaterialButtonToggleGroup toggleButton = findViewById(R.id.toggleButton);
toggleButton.addOnButtonCheckedListener();
// I CAN'T FIND ANY PROPER SOLUTION
Solution
You can use the getCheckedButtonId()
method.
Something like:
MaterialButtonToggleGroup materialButtonToggleGroup =
findViewById(R.id.toggleButton);
int buttonId = materialButtonToggleGroup.getCheckedButtonId();
MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
Only if you need a listener you can use the addOnButtonCheckedListener
:
materialButtonToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
@Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if (isChecked) {
if (checkedId == R.id.button1) {
//..
}
}
}
});
You have to check the checkedId
value but also the isChecked
value. The same listener is called when you check a button but also when you unckeck a button.
It means that if you click the button1
the listener is called with isChecked=true
and checkedId=1
. Then if you click the button2
the listener is called twice. Once with isChecked=false
and checkedId=1
, once with isChecked=true
and checkedId=2
.
Answered By - Gabriele Mariotti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.