Reset a Radio button inside a Radio group - android

How I reset a radio button inside a radio group like the image example below
All my radio groups and its radio buttons are created programmatically.
I tried to to set OnClickListener to get the radio button value before getting changed but, it didn't help.
Edit: I posted the answer below, please check it.

try this :
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
if (checkedId == R.id.radioButton){
//do something
}
else if(checkedId == R.id.radioButton2){
}
else{
}
});
xml layout
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="#+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="#+id/radioGroup"
android:layout_alignLeft="#+id/textView2"
android:layout_alignStart="#+id/textView2"
android:layout_alignRight="#+id/textView3"
android:layout_alignEnd="#+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="#+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="#+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>

You have to uncheck one radiobutton while checking the other.
Simple way.
public void clearRadioChecked() {
alt1.setChecked(false);
blt2.setChecked(false);
}
if you want to select alt1 then on click of alt1 do as below.
clearRadioChecked()
alt1.setChecked(true);

This is how I did it:
It is in C# but I think it is easy to convert it to Java.
I used tag to know if this radio button checked before or not.
False => It is not checked
True => It is checked
radiobutton.Tag = false;
radiobutton.Click += SingleChoiceQuestionAlternativeClick;
Then:
private void SingleChoiceQuestionAlternativeClick(object sender, EventArgs e)
{
RadioButton questionAlternative = sender as RadioButton;
if (questionAlternative != null)
{
RadioGroup questionAlternatives = questionAlternative.Parent as RadioGroup;
if (questionAlternatives != null)
{
if (questionAlternative.Tag.Equals(false))
{
for (int i = 0; i < questionAlternatives.ChildCount; i++)
{
RadioButton childRadioButton = questionAlternatives.GetChildAt(i) as RadioButton;
if (childRadioButton != null)
{
childRadioButton.Tag = false;
}
}
questionAlternative.Tag = true;
}
else
{
questionAlternative.Tag = false;
questionAlternatives.ClearCheck();
}
}
}
}

Related

How to use if else ladder in android while dealing with radio buttons

The following is the code that I am currently using in the OnClick method for using a radio button.
switch(view.getId()) {
case R.id.op1_radio_button:
if (checked) {
score=0;
break;
}
I am looking for an if-else version of the code so that it would be easier for me to use radio buttons.
Try this
int id = view.getId();
if(id == R.id.op1_radio_button){
//do something
}else if(id == R.id.button2){
//do something else
}
you should use RadioGroup to manage RadioButton selection like this in your XML,
<RadioGroup
android:checkedButton="#id/rbtn_male"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rbtn_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Male" />
<RadioButton
android:id="#+id/rbtn_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Female" />
</RadioGroup>
now, to manage the click on RadioButton in Your Activity add this,
RadioButton rbMale = findViewById(R.id.rbtn_male);
RadioButton rbFemale = findViewById(R.id.rbtn_female);
rbMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
score = 1;
}
});
rbFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
score = 0;
}
});
I hope this is the best answer for your case.

How to set value of a radio button inside a radio group android

I'm trying to use radio groups where it has 2 radio buttons inside. I wanted to set a value for each radio buttons like for example the value is male and female. After that when I have already click on of my radio button it will display the value selected. How can you achieve this? Thank you for the help.
i have tried something like this just to test on how will i set a value
public void onRadioButtonClicked(View radioButton) {
int count = radioGroup.getChildCount();
for (int i = 0; i < count; i++) {
View o = radioGroup.getChildAt(i);
if (o instanceof RadioButton) {
RadioButton radioBtn = (RadioButton)o;
// get the state
boolean isChecked = radioBtn.isChecked();
// to set the check
radioBtn.setChecked(true);
}
}
}
but i think its not what i'm looking for.
i have already tried radioGroup.setId() assuming that the radio buttons have values already but it just display nonsense number.
You should use a RadioGroup and an OnCheckedChangeListener in your code to detect when a RadioButton is selected. In your layout XML:
<RadioGroup
android:id="#+id/radioGroup"
... >
<RadioButton
android:id="#+id/radioButton1"
... />
<RadioButton
android:id="#+id/radioButton2"
... />
</RadioGroup>
In your Activity/Fragment, set up like so:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangedListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
<type> value = <default value>;
switch (checkedId) {
case R.id.radioButton1:
value = ...;
break;
case R.id.radioButton2:
value = ...;
break;
}
// do something with value
}
});
Make sure that your radio buttons are wrapped in a radio group like below:
<RadioGroup
android:id="#+id/myRadioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radioGroupButtonMale"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<RadioButton
android:id="#+id/radioGroupButtonFemale"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"/>
</RadioGroup>
And in code, to set the value,
RadioGroup mySelection = (RadioGroup)findViewById(R.id.myRadioGroup);
int radioButtonId = mySelection.getCheckedRadioButtonId();
String selectedValue;
switch (radioButtonId)
{
case R.id.radioGroupButtonMale:
selectedValue = "Value for Male";
break;
case R.id.radioGroupButtonFemale:
selectedValue = "Value for Female";
break;
}

RadioButtons in RadioGroup arent working as intended

I have a RadioGroup with two RadioButton's:
<RadioGroup
android:id="#+id/main_radiogroup_lock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/main_layout_lock_dummy"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/main_radiobutton_lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="110dp"
android:background="#drawable/custom_radiobutton_lock"
android:button="#null"
android:contentDescription="#string/imageview_description" />
<RadioButton
android:id="#+id/main_radiobutton_unlock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="230dp"
android:background="#drawable/custom_radiobutton_unlock"
android:button="#null"
android:checked="true"
android:contentDescription="#string/imageview_description" />
</RadioGroup>
I initialize the RadioButton's and set an OnCheckedChangeListener:
...
this.radioButtonLock = (RadioButton) view.findViewById(R.id.main_radiobutton_lock);
this.radioButtonLock.setOnCheckedChangeListener(this);
this.radioButtonUnlock = (RadioButton) view.findViewById(R.id.main_radiobutton_unlock);
this.radioButtonUnlock.setOnCheckedChangeListener(this);
...
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(view.getId() == R.id.main_radiobutton_lock) {
Log.v("MainFragment", "Lock");
this.imageButtonLanguage.setEnabled(false);
this.buttonOpen.setEnabled(false);
this.buttonAutomatic.setEnabled(false);
this.buttonClose.setEnabled(false);
this.buttonFog.setEnabled(false);
this.checkBoxRed.setEnabled(false);
this.checkBoxGreen.setEnabled(false);
this.checkBoxBlue.setEnabled(false);
return;
} else if(view.getId() == R.id.main_radiobutton_unlock) {
Log.v("MainFragment", "Unlock");
this.imageButtonLanguage.setEnabled(true);
this.buttonOpen.setEnabled(true);
this.buttonAutomatic.setEnabled(true);
this.buttonClose.setEnabled(true);
this.buttonFog.setEnabled(true);
this.checkBoxRed.setEnabled(true);
this.checkBoxGreen.setEnabled(true);
this.checkBoxBlue.setEnabled(true);
return;
}
}
So when i now start the app my radioButtonUnlock is checked. When i know chec the radioButtonLock nothing happens and no log output but the checked image is set so the checking is working. When i after that again check the radioButtonUnlock the following output appears:
02-04 09:59:31.355: V/MainFragment(533): Lock
02-04 09:59:31.355: V/MainFragment(533): Unlock
So both RadioButton's are fired. After that everytime i press one of the RadioButton's all events are fired. After pressing the radioButtonLock the following happens:
02-04 09:59:32.850: V/MainFragment(533): Unlock
02-04 09:59:32.850: V/MainFragment(533): Lock
Whats the point of that? I set different ID's so why are always both RadioButtons's fired?
Try this hope will work -
1)set check change listener to radio group
RedioGroup rg =(RadioGroup)findviewByid(R.id.main_radiogroup_lock);
rg.setcheckchangedlistener(true);
2)handle on check change listener event
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.rdb1:
radio_selected = R.id.rdb1;
Toast.makeText(getApplicationContext(),"first",Toast.LENGTH_LONG).show();
case R.id.rdb2:
radio_selected = R.id.rdb2;
Toast.makeText(getApplicationContext(),"second",Toast.LENGTH_LONG).show();
}
}

how to loop RadioGroup Android

Im newbiew to programming, i want create some quiz app.
all the answer just use radio button user must choose : 1 or 2 or 3 or 4, all the question have same radiobutton text, the answer just from 1 to 4.
i already read how to loop dynamic just radiobutton but how to loop RadioGroup because i just need the number for each question and insert into array,
this is my xml :
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#color/black"
android:text="0"
android:button="#null"
android:drawableTop="#android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1"/>
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#color/black"
android:text="1"
android:button="#null"
android:drawableTop="#android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#color/black"
android:text="2"
android:button="#null"
android:drawableTop="#android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#color/black"
android:text="3"
android:button="#null"
android:drawableTop="#android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1" />
</RadioGroup>
and this is the result : http://tinypic.com/r/2uzs50g/8
i thought if i can just loop radiogroup dynamic with same radiobutton for each question i can just get radiogroup id and insert into array. if you have other sugestion how i should create something like that please tell. thanks for your help all
Try this :-
RadioGroup rg = (RadioGroup) findViewById(radiogroupid);
String rg_selected_data = "";
int radioButtonId= rg.getCheckedRadioButtonId();
switch (radioButtonId) {
case YouRadioButtonIdOne:
rg_selected_data = "1";
break;
case YouRadioButtonIdtTwo:
rg_selected_data = "2";
break;
case YouRadioButtonIdtThree:
rg_selected_data = "3";
break;
case YouRadioButtonIdtFour:
rg_selected_data = "4";
break;
}
Now you can find which radiobutton is selected.
Try this code if you face any problem I will help you. :)
This solution will run code every time a radio button is checked. It goes in your onCreate(). Source is from here.
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
int questionCounter = 0;
int numberCorrect = 0;
//Question 1 is A, Q2 is C, Q3 is D, Q4 is B, Q5 is A again
final char[] correctAnswersList = {'a', 'c', 'd', 'b', 'a'};
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
switch (checkedId) {
case (R.id.radio_button_a):
if (questionCounter==0 || questionCounter==4){
numberCorrect++;
}
break;
}
case (R.id.radio_button_b):
if (questionCounter==3){
numberCorrect++;
}
break;
}
case (R.id.radio_button_c):
if (questionCounter==1){
numberCorrect++;
}
break;
}
case (R.id.radio_button_d):
if (questionCounter==2){
numberCorrect++;
}
break;
}
}
});
There is a problem with my code, which was on purpose, since it's finals season in America, and students like to come here last minute to cheat. You'll find it if you look. You wouldn't use looping with this kind of problem, I'm not sure why that's a requirement.
for all who want create some quesioner like my self this code will help you, this code will loop RadioGroup and get the value from allradiogroup use List. and thanks for all people who help
private List<RadioGroup> allradioGroup = new ArrayList<RadioGroup>();
private RadioGroup radioGroup;
private List<RadioButton> allRadio = new ArrayList<RadioButton>();
private RadioButton radioButton;
// place inside oncreate or whatever you want
//your linear layout ID
LinearLayout linear = (LinearLayout) findViewById(R.id.lintes);
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 20; i++) {
/* Defining RadioGroup */
radioGroup = new RadioGroup(this);
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
allradioGroup.add(radioGroup);
/* Displaying Radio Buttons */
for (int j = 0; j < 4; j++) {
radioButton = new RadioButton(this);
//you can set your button ID here
radioButton.setId(j);
allRadio.add(radioButton);
//set text for each ID
if (allRadio.get(j).getId() == 0) {
radioButton.setText("0");
} else if (allRadio.get(j).getId() == 1) {
radioButton.setText("1");
} else if (allRadio.get(j).getId() == 2) {
radioButton.setText("2");
} else if (allRadio.get(j).getId() == 3) {
radioButton.setText("3");
}
//number 4 is total radiobutton
allradioGroup.get(i).addView(allRadio.get(i*4+j),j,layoutParams);
}
// set text
TextView soal = new TextView(this);
soal.setText("\n"+i+".loop your question here");
linear.addView(soal);
linear.addView(allradioGroup.get(i));
}
and this code will get value from list, just loop (i) and you will get all the value
int id[i] = allradioGroup.get(i).getCheckedRadioButtonId();

Android: How to get a radiogroup with togglebuttons?

I want a group of buttons where a user can choose one of them as option. It has to be a radiobuttongroup like behaviour, but I don't want the radio circle to be present. I just want the user to be able to toggle only one of the buttons.
I think I would need someting like a togglegroup.
Does something like this exist in Android?
I'd just re-use the RadioGroup like so: (please note the onClick attribute,i.e. a button click will trigger your Activity's onToggle(View) method.
<RadioGroup android:id="#+id/toggleGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal"
>
<ToggleButton android:id="#+id/btn_Letter"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textSize="14sp"
android:textOn="Letter"
android:textOff="Letter"
android:onClick="onToggle"
android:checked="true"
/>
<ToggleButton android:id="#+id/btn_A4"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textSize="14sp"
android:textOn="A4"
android:textOff="A4"
android:onClick="onToggle"
/>
</RadioGroup>
In your Activity, or some place else, you can define a listener, e.g.
static final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
and register it, for instance in onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.scan_settings);
((RadioGroup) findViewById(R.id.toggleGroup)).setOnCheckedChangeListener(ToggleListener);
}
finally in onToggle(View), you would do whatever needs to happen, specific to your app. and also call the RadioGroup's check method, with the toggled view's id. Like so:
public void onToggle(View view) {
((RadioGroup)view.getParent()).check(view.getId());
// app specific stuff ..
}
You can use regular radio buttons and use an image for the RadioButton background and don't specify a text string:
<RadioButton
android:id="#+id/custom_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#null"
android:background="#drawable/button_custom"
/>
For the background, use any drawable, but most likely you'll want to use a selector to be able to provide different images for the different states. The simplest version uses just two images:
<item android:state_checked="true" android:state_pressed="true"
android:drawable="#drawable/custom_selected" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="#drawable/custom_normal" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="#drawable/custom_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="#drawable/custom_normal" />
<item android:state_checked="false" android:drawable="#drawable/custom_normal" />
<item android:state_checked="true" android:drawable="#drawable/custom_selected" />
With this, the radio button looks like a regular button (or rather, looks like whatever drawable you provided) and behaves like a radio button in a radio group.
I tried all the methods outlined above and none really worked that well.
Trying to hack a radiobutton to look like a real button looks bad.
Eventually I just took the RadioGroup source code and Modified it to accept a ToggleButton rather than a RadioButton. Works really well!
Here is the source on Github: ToggleGroup
Usage:
<com.rapsacnz.ToggleGroup
android:id="#+id/deal_detail_toolbar"
android:layout_width="fill_parent"
android:layout_height="60dip"
android:layout_alignParentBottom="true"
android:background="#drawable/bgnd_toggle_button">
<ToggleButton
android:id="#+id/b1"
android:textOn="#string/tab_1_label"
android:textOff="#string/tab_1_label"
android:textSize="10sp"
android:textColor="#color/tab_button_color"
android:checked="true"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:drawableTop="#drawable/toggle_spotlight"
android:drawablePadding="-5dp "
android:gravity="bottom|center"
android:paddingTop="10dp"
android:paddingBottom="5dp"
android:background="#drawable/bgnd_transparent" />
<ToggleButton
android:id="#+id/b2"
android:textOn="#string/tab_2_label"
android:textOff="#string/tab_2_label"
android:textSize="10sp"
android:textColor="#color/tab_button_color"
android:checked="false"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:drawableTop="#drawable/toggle_browse"
android:gravity="bottom|center"
android:paddingTop="10dp"
android:paddingBottom="5dp"
android:background="#drawable/bgnd_transparent" />
<ToggleButton
android:id="#+id/b3"
android:textOn="#string/tab_3_label"
android:textOff="#string/tab_3_label"
android:textSize="10sp"
android:textColor="#color/tab_button_color"
android:checked="false"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:drawableTop="#drawable/toggle_purchased"
android:gravity="bottom|center"
android:paddingTop="10dp"
android:paddingBottom="5dp"
android:background="#drawable/bgnd_transparent" />
</com.rapsacnz.ToggleGroup>
Hope this helps
Here is how I managed to do it (no RadioGroup involved):
private CompoundButton.OnCheckedChangeListener toggleListener = new CompoundButton.OnCheckedChangeListener()
{
boolean avoidRecursions = false;
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(avoidRecursions) return;
avoidRecursions = true;
// don't allow the un-checking
if(!isChecked)
{
buttonView.setChecked(true);
avoidRecursions = false;
return;
}
// un-check the previous checked button
if(buttonView != toggleButton1 && toggleButton1.isChecked()) toggleButton1.setChecked(false);
else if(buttonView != toggleButton2 && toggleButton2.isChecked()) toggleButton2.setChecked(false);
else if(buttonView != toggleButton3 && toggleButton3.isChecked()) toggleButton3.setChecked(false);
else if(buttonView != toggleButton4 && toggleButton4.isChecked()) toggleButton4.setChecked(false);
avoidRecursions = false;
}
};
// ...
toggleButton1.setOnCheckedChangeListener(toggleListener);
toggleButton2.setOnCheckedChangeListener(toggleListener);
toggleButton3.setOnCheckedChangeListener(toggleListener);
toggleButton4.setOnCheckedChangeListener(toggleListener);
I'm using Kotlin and I tried Wolf Paulus's answer and it didn't work well for me.
I played around with it and was able to make it work in the following way:
First, I removed the "onClick" from the xml:
<RadioGroup android:id="#+id/toggleGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal"
>
<ToggleButton android:id="#+id/btn_Letter"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textSize="14sp"
android:textOn="Letter"
android:textOff="Letter"
android:checked="true"
/>
<ToggleButton android:id="#+id/btn_A4"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textSize="14sp"
android:textOn="A4"
android:textOff="A4"
/>
</RadioGroup>
I didn't use the ToggleListener, instead, inside the onCreate() I listened to each of the ToggleButtons I have:
btn_Letter.setOnClickListener { it -> onToggle(it) }
btn_A4.setOnClickListener { it -> onToggle(it) }
And the most important part, the onToggle(btn: View)
private fun onToggle(btn: View) {
val radioGroup = (btn.parent as RadioGroup)
for (index in 0 until radioGroup.childCount) {
val child = radioGroup.getChildAt(index) as ToggleButton
child.isChecked = child.id == btn.id
// do what ever else you need to do
}
}
This is it. I hope this helps.
my solution achieves the same effect but without using the radiobuttons.
For the xml, first un "selector" in "#drawable/myselectorfile":
<?xml version="1.0" encoding="UTF-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false"
android:drawable="#drawable/icon_off" />
<item android:state_checked="true"
android:drawable="#drawable/icon_on" />
</selector>
un file for items of my listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtInfo"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:paddingTop="15dip" />
<ToggleButton
android:id="#+id/BtnToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="14dp"
android:background="#drawable/toggle_style"
android:padding="10dip"
android:textOff=""
android:textOn=""
android:focusable="false"/>
</LinearLayout>
and my listview :
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lv_lista"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
in the oncreate methode:
lista.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onItemClick(AdapterView<?> pariente, View view, int posicion, long id) {
#SuppressWarnings("unused")
ListEntity elegido = (ListEntity) pariente.getItemAtPosition(posicion);
varToggle = (ToggleButton) view.findViewById(R.id.BtnToggle);
varToggle.setChecked(true);
// showDialog(0); // dialog optional
//restart btn's
reStart(posicion);
}
});
in the Activity class:
#Override
protected Dialog onCreateDialog(int id){
Dialog dialogo = crearDialogoConfirmacion();
return dialogo;
}
public void reStart(int posicion){
for(int j=0;j<lista.getCount();j++)
{
View vista = lista.getChildAt(j);
ToggleButton varToggle2 = (ToggleButton) vista.findViewById(R.id.BtnToggle);
if(j != posicion){ varToggle2.setChecked(false); }
}
}
I did it with LinearLayout instead of RadioGroup, using ButterKnife:
#BindViews({R.id.one, R.id.two, R.id.three})
List<ToggleButton> toggleGroup;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
ButterKnife.bind(this, view);
}
#OnClick({R.id.one, R.id.two, R.id.three})
public void toggle(ToggleButton selected) {
if (selected.isChecked()) {
// Deselect other buttons
for (ToggleButton button : toggleGroup) {
if (button.getId() != selected.getId()) {
button.setChecked(false);
}
}
} else {
// Disallow deselecting the current button
selected.toggle();
}
}
So you want buttons from that only one can be selected at a time?
If you don't show the radio button how does the user know what she has selected?
You can work with RadioButton and RadioGroup but I don't know if you easily can generate a custom radio button with a look more suitable to your app. But it should be possible somehow if you can extend the radiobutton itself and override the draw method, or look what kid of buttons can be integrated in a radiogroup. Maybe you can implement a special interface for your view and then join some of your custom buttons together in one radiogroup.
Using any container ViewGroup add your CompoundButtons (CheckBox, RadioButton, Switch, SwitchCompat, ToggleButton) and then inside your onCheckedChanged call a utility function to clear the other buttons.
<LinearLayout
android:id="#+id/toggle_group"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ToggleButton
android:id="#+id/toggle_btn1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textOff="Off1"
android:textOn="On1" />
<View
android:layout_width="2dp"
android:layout_height="match_parent"
android:layout_margin ="8dp"
android:background="#ffff" />
<ToggleButton
android:id="#+id/toggle_btn2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textOff="Off2"
android:textOn="On2" />
</LinearLayout>
Inside your onCheckedChanged, deal with the state change and call the utility method to clear the other children. The following supports all view container groups which are derived from ViewGroup and allows you to mixed non-CompoundButton objects in the container. Since you often have a onCheckedChanged callback already, there only new code is to call the utility function.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
switch (id) {
case R.id.toggle_btn1:
if (isChecked) {
doBtn1Action();
doRadioGroupChange((ViewGroup)buttonView.getParent(), id);
}
break;
case R.id.toggle_btn2:
if (isChecked) {
doBtn2Action();;
doRadioGroupChange((ViewGroup)buttonView.getParent(), id);
}
break;
And here is the utility function to clear children.
/**
* Emulate radioGroup and clear buttons which don't match checkedId.
* #param viewGroup
* #param checkedId
*/
private static void doRadioGroupChange(final ViewGroup viewGroup, final int checkedId) {
for (int rgIdx = 0; rgIdx < viewGroup.getChildCount(); rgIdx++) {
View child = viewGroup.getChildAt(rgIdx);
if (child instanceof CompoundButton) {
final CompoundButton view = (CompoundButton) viewGroup.getChildAt(rgIdx);
view.setChecked(view.getId() == checkedId);
}
}
}
public void OnTabSelected(View v){
RadioGroup radioGroup = (RadioGroup)v.getParent();
for (int j = 0; j < radioGroup.getChildCount(); j++) {
ToggleButton toggleButton = (ToggleButton) radioGroup.getChildAt(j);
toggleButton.setChecked(v.getId() == toggleButton.getId());
}
}
Kotlin version:
for(index in 0..(radioGroup.childCount-1))
(radioGroup.getChildAt(index) as ToggleButton).isChecked = false

Categories

Resources