Ensure one of the RadioButton in a RadioGroup is selected in Android - android

If I have the following radiogroup:
<RadioGroup
android:id="#+id/rgType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="6" >
<RadioButton
android:id="#+id/rbBrides"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Bridge" />
<RadioButton
android:id="#+id/gbTunnel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tunnel" />
<RadioButton
android:id="#+id/rbHighway"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Highway" />
</RadioGroup>
And I want to do the following check:
If (rgType is selected) {
system.out.println("ok");
}
if (rgType is void/null/not selected) {
system.out.println("choose at least one selection");
}
Can I use isChecked() which is used for individual radio buttons, like the following?
if (rgType.isChecked()) {
}
else {
}

You can use getCheckedRadioButtonId and see if one of your RadioButtons is checked. I'm not exactly sure what it returns if none are but probably either null or more likely -1. Either way, run that and see what it returns.
I believe it does return -1 if nothing checked so try
if (rgType == -1)
{
system.out.println("choose at least one selection");
}
else
{
system.out.println("ok");
}
RadioGroup

Related

Hides the view when the button is clicked

I have a radio group used to set data class properties. Here's how I've gone so far: I manually set the "bankDestination" view to invisible if proxy_bi_fast is checked. However the "bankDestination" view is still visible.
fun onRadioButtonClicked(view: View) {
if (view is RadioButton) {
val checked = view.isChecked
when (view.getId()){
R.id.proxy_BI_Fast ->
if (checked) {
binding.bankDestination.visibility = View.GONE
}
}
}
}
the related xml code:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/account_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:text="#string/account_number"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/proxy_BI_Fast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="20dp"
android:text="#string/proxy_bi_fast" />
</RadioGroup>
You haven't added onClick method in your proxy_BI_Fast radio button. Try adding that and then check.
It wont' work android:onClick="onRadioButtonClicked" in the RadioButton instead of this you have to use setOnCheckedChangeListener on the RadioGroup as describe below.
binding.rbGroup.setOnCheckedChangeListener { group, checkedId ->
when (checkedId) {
R.id.proxy_BI_Fast -> {
binding.bankDestination.visibility = View.GONE
}
}
}

error event onclick of RadioButton in .xml

When I add an on click event in .xml I don't have and error like this
Here is my code
<RadioButton
android:id="#+id/dientich"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickHandler"
android:text="dien tich" />
<RadioButton
android:id="#+id/thetich"
android:onClick=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="the tich" />
</RadioGroup>
Thank you!
I think that the better way is to set a listener in your code
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
when (optionId) {
R.id.dientich -> {
// do something when radio button dientich is selected
}
R.id.thetich -> {
// do something when radio button thetich is selected
}
}
}
Can you please refer to this link
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User 1"
android:onClick="onRadioButtonClicked"/>
public void onRadioButtonClicked(View view) {
//your code
}
https://developer.android.com/guide/topics/ui/controls/radiobutton

Radio Button setChecked/setSelected not working

I have a list view with a text and 3 radio button. If i select any radio button, and scroll the list the radio button gets un-selected. I am maintaining the ID of items for which radio button is selected and in adapter Getview setting the required radio button to be selected. On debugging, it's executing statement setChecked(true) but the radio button is still unchecked. I tried setSelected(true) and setting through radio group ((RadioButton)holder.rg.getChildAt(2)).setChecked(true); but nothing seem to be working.
XML:
<TextView
android:id="#+id/refill_product_name"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="#string/hello_world"
android:textColor="#android:color/black"
android:textStyle="normal"
android:textSize="#dimen/item_sub_heading"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"/>
<RadioGroup
android:id="#+id/refill_product_rg"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<RadioButton
android:id="#+id/refill_product_regular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/regular"
android:textColor="#android:color/black"
android:textStyle="bold"
android:buttonTint="#color/primary"/>
<RadioButton
android:id="#+id/refill_product_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/small"
android:textColor="#android:color/black"
android:textStyle="bold"
android:layout_marginLeft="#dimen/radio_btn_margin"
android:buttonTint="#color/primary"/>
<RadioButton
android:id="#+id/refill_product_extra_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/extra_small"
android:textColor="#android:color/black"
android:textStyle="bold"
android:layout_marginLeft="#dimen/radio_btn_margin"
android:buttonTint="#color/primary"/>
</RadioGroup>
Adapter Code:
private class ViewHolder {
TextView productName;
RadioButton regularBtn, smallBtn, extraSmallBtn;
RadioGroup rg;
}
GetView Method in Adapter
holder.rg.clearCheck();
if (mAppSession.getSelRefillProducts() != null) {
for (RefillProduct pr : mAppSession.getSelRefillProducts()) {
if (pr.getProductId() == rf.getProductId()) {
if (pr.getSize().equals("R")) {
((RadioButton)holder.rg.getChildAt(0)).setChecked(true);
} else if (pr.getSize().equals("S")) {
holder.smallBtn.setSelected(true);
} else if (pr.getSize().equals("XS")) {
((RadioButton)holder.rg.getChildAt(2)).setChecked(true);
}
}
}
}
I am not sure if I am missing something, but setChecked or setSelected is not working. Please advise.
Try this, before setting radio button to checked, clear all the checks in the radio group:
yourRadioGroup.clearCheck();
yourRadioButton.setChecked(true);
I solved this by removing if (convertView == null) and the else part from getView method in adapter.
else {
holder = (ViewHolder) convertView.getTag();
It is an expected behavior of ListView since it reuses the View for each item. Consider tracking the checkbox checked state using a SparseBoolArray. Check out this link: Getting the state of a checkbox inside of a listview

How to set only one RadioButton Can be selected at the time in RadioGroup

I've created a radio button in radiogroup, but when I try running the apps all radio button can be selected all the time, and how to set only one radiobutton can be selected at one time?
I'm using Fragment
RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.RGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.Abdominal) {
Toast.makeText(getActivity().getApplicationContext(), "choice: A",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Arm) {
Toast.makeText(getActivity().getApplicationContext(), "choice: B",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Back){
Toast.makeText(getActivity().getApplicationContext(), "choice: C",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Chest){
Toast.makeText(getActivity().getApplicationContext(), "choice: D",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Leg){
Toast.makeText(getActivity().getApplicationContext(), "choice: E",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.Shoulder){
Toast.makeText(getActivity().getApplicationContext(), "choice: F",
Toast.LENGTH_SHORT).show();
}
}
});
here my xml code for RG and RB
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RGroup">
<TableRow android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdominal"
android:id="#+id/Abdominal"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Arm"
android:id="#+id/Arm"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/Back" />
</TableRow>
<TableRow>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chest"
android:id="#+id/Chest"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leg"
android:id="#+id/Leg"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoulder"
android:id="#+id/Shoulder"/>
</TableRow>
</RadioGroup>
EDITED 1 : Answer :
If you dont want radio button can be selected in one time, so dont use Tablerow
It's not working because of TableRow inside RadioGroup. All RadioButtons are not grouped together because of TableRow between them.
RadioButton should be the direct child of RadioGroup, Otherwise grouping does not work.
Just change your code like this it will work :
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Abdominal"
android:id="#+id/Abdominal"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Arm"
android:id="#+id/Arm"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/Back" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chest"
android:id="#+id/Chest"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leg"
android:id="#+id/Leg"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoulder"
android:id="#+id/Shoulder"/>
</RadioGroup>
Hope this helps. :)
I have noticed that single selection does not work without setting id to radio buttons.
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/expenseRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/expense" />
<RadioButton
android:id="#+id/incomeRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/income" />
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Debit"
android:id="#+id/rDebit"
android:checked="false"
/>
<RadioButton
android:layout_width="0dp"
android:layout_weight="50"
android:layout_height="wrap_content"
android:text="Credit"
android:id="#+id/rCredit"
android:checked="false" />
</RadioGroup>
And in java file
RadioGroup radioGroup;
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
And when to do something
if (radioGroup.getCheckedRadioButtonId() == R.id.rCredit)
{
// do something
}
I encountered the same issue and found where I was making mistakes, i'm describing it below:
If you are using RadioButtons in RadioGroup, then RadioButtons should be Direct Child of RadioGroup.
Check first condition, if it is correct then give id to RatioButton and run project, It will solve the problem automatically.
Simple way. onclick of radio button. do code as per below.
public void clearRadioChecked() {
rdopa.setChecked(false);
rdopb.setChecked(false);
rdopc.setChecked(false);
rdopd.setChecked(false);
}
if you wann select rdopa then on click of rdopa do as below.
clearRadioChecked()
rdopa.setChecked(true);
You can use android:checkedButton attribute on RadioGroup, providing the id of the RadioButton you want to be checked initially and selecting another RadioButton will clear the previous selection.
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="#+id/rbNo"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:text="Yes" />
<RadioButton
android:id="#+id/rbNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No" />
</RadioGroup>
You can create your own RadioGroup, that is able to find all RadioButtons that are nested in your group regardless of direct child or not. Below the code of my NestedRadioGroup. Using this instead of your RadioGroup in your xml file should do the trick.
public class NestedRadioGroup extends LinearLayout {
private SparseArray<RadioButton> radioButtons;
private int checkedId;
public NestedRadioGroup(Context context) {
this(context, null);
}
public NestedRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
radioButtons = new SparseArray<>();
checkedId = -1;
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
findRadioButtons(child);
}
private void findRadioButtons(View child) {
if (child instanceof RadioButton) {
RadioButton newButton = (RadioButton) child;
newButton.setId(radioButtons.size());
newButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
if (checkedId != -1) {
radioButtons.get(checkedId).setChecked(false);
}
radioButtons.get(buttonView.getId()).setChecked(true);
checkedId = buttonView.getId();
}
});
radioButtons.put(newButton.getId(), newButton);
} else if (child instanceof ViewGroup) {
ViewGroup group = (ViewGroup) child;
for (int i = 0; i < group.getChildCount(); i++) {
this.findRadioButtons(group.getChildAt(i));
}
}
}
}
Any ideas to make the code cleaner?
I hope it works out for you :)
We can use any layout like LinearLayout, RelativeLayout, ConstraintLayout or GridLayout as RadioGroup using the following method in Kotlin.
For the following example I used ConstraintLayout to get fixed width and height for RadioButton.
layout.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/rbYellow"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="#dimen/space_2x"
android:layout_marginEnd="#dimen/space"
android:gravity="center"
android:text="Yellow"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toStartOf="#+id/rbOrange"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="spread_inside"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RadioButton
android:id="#+id/rbOrange"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="#dimen/space"
android:layout_marginEnd="#dimen/space"
android:gravity="center"
android:text="Orange"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="#id/rbYellow"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toStartOf="#+id/rbRed"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/rbYellow"
app:layout_constraintTop_toTopOf="#id/rbYellow" />
<RadioButton
android:id="#+id/rbRed"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="#dimen/space"
android:layout_marginEnd="#dimen/space"
android:gravity="center"
android:text="Red"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="#id/rbYellow"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toStartOf="#+id/rbGreen"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/rbOrange"
app:layout_constraintTop_toTopOf="#id/rbYellow" />
<RadioButton
android:id="#+id/rbGreen"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="#dimen/space"
android:layout_marginEnd="#dimen/space_2x"
android:gravity="center"
android:text="Green"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="#id/rbYellow"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/rbRed"
app:layout_constraintTop_toTopOf="#id/rbYellow" />
</androidx.constraintlayout.widget.ConstraintLayout>
Kotlin code
radioGroup.children.forEach { aBtn ->
(aBtn as RadioButton).setOnCheckedChangeListener { button, isChecked ->
if(isChecked) {
radioGroup.children.forEach { bBtn ->
if(bBtn.id != button.id) {
(bBtn as RadioButton).isChecked = false
}
}
}
}
}

how to dynamically change the value of the find view by id in android?

i am a basic learner in android. What i am trying to achieve from my code is that : i want to dynamically change the value of radio buttons of a radio group inside a for loop. Then, grab the text value so that i can compare, lets say if the value is "Take Out", i want the rb1 to be checked.
Here is the radio group
<RadioGroup
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:layout_alignBottom="#+id/add"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="20dp"
android:id="#+id/rg1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Out"
android:id="#+id/rb1"
android:checked="true"
android:onClick="selectSomething"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sit down"
android:id="#+id/rb2"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delivery"
android:id="#+id/rb3"
android:checked="false" />
</RadioGroup>
What i have tried so far:
int count = rg1.getChildCount();
//Make checked if the value is equal
for(int i = 0; i < count;i++){
String myshit = "rb"+i;
int id = getResources().getIdentifier(myshit, "id", getPackageName());
RadioButton RadioValue = (RadioButton) findViewById(id);
String _RadioValue = RadioValue.getText().toString();
Log.d("abc",_RadioValue);
}
For testing, i wanted to print out the values in Log but it does not compile and throws error. I am just half way thorugh in my code. Is there a better way to solve this problem ? Need your expertise. Thank You !
You are doing it the wrong way.
All of your RadioButtons should point to a common function.
That is, all of them should have this property assigned:
android:onClick="selectSomething"
Inside that method, do something like:
public final void selectSomething(final View v)
{
switch(v.getId())
{
case R.id.rb1:
{
String str = "Take out";
System.out.println(str);
break;
}
// all other cases
// ...
}
}

Categories

Resources