How to get the selected index of dynamically added radio buttons - android

I had added radio buttons dynamically like below.
for (int i = 0; i< typeArrayList.size(); i++) {
radioButtons[i] = new RadioButton(MainActivity.this);
radioButtons[i].setId(i);
radioButtons[i].setText(typeArrayList.get(i).toString());
if(i==0) {
radioButtons[i].setChecked(true);
}
typeLayout.addView( radioButtons[i]);
}
I have a button when clicked calls a method to which the selected item (text) of the dynamically added radio buttons should be passed . How can I get the selected radio button text for the dynamically added radio buttons?

Its very important to set your radio button id when adding buttons to a radio group.
RadioButton rb = new RadioButton(context);
rb.setText(option);
rb.setId(rb.hashCode());
radioGroup.addView(rb);
radioGroup.setOnCheckedChangeListener(mCheckedListner);
Now in your click listener check for the unique id.
private RadioGroup.OnCheckedChangeListener mCheckedListner = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
JSONArray actionArray = new JSONArray();
if(group.findViewById(checkedId)!=null) {
RadioButton rb = ((RadioButton) group.findViewById(checkedId)).getText();
//Your Code here
}
}
}
};

You have stored all RadioButtons that you create dynamically in a radioButtons array.
So if you want to know which radiobutton is selected you can loop all this array and check each RadioButton
for (int i = 0; i< radioButtons.size(); i++) {
if(radioButtons[i].isChecked()){
// selected radio button is here
String text = radioButtons[i].getText();
}
}

First you have to get all childs of your view. Then check if this view is RadioButton. And at last check which button is checked.
int childcount = typeLayout.getChildCount();
for (int i=0; i < childcount; i++){
View view = typeLayout.getChildAt(i);
if (view instanceof RadioButton) {
if(((RadioButton)view).isChecked()) {
RadioButton yourCheckedRadioButton = (RadioButton) typeLayout.getChildAt(i); // this is your checked RadioButton
}
}
}

#Komali Shirumavilla
Add those dynamic radio buttons to radio group
so add following lines in your code
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
for (int i = 0; i< typeArrayList.size(); i++) {
radioButtons[i] = new RadioButton(MainActivity.this);
radioButtons[i].setId(i);
radioButtons[i].setText(typeArrayList.get(i).toString());
if(i==0) {
radioButtons[i].setChecked(true);
}
rg.addView(radioButtons[i]); // add dynamic radio buttons to radio group
}
typeLayout.addView(rg); // add radio group to view
Now set setOnCheckedChangeListener on the RadioGroup
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId) {
RadioButton btn = (RadioButton)findViewById(checkedId);
Log.d("Your selected radio button id",btn.getText());
}
}
});

This can be simply achieved using tags.
While adding the RadioButton set a tag that particular object. In your case, set the tag to be the text of the radio button,
radioButtons[i].setTag(typeArrayList.get(i).toString());
This way all your radio buttons will have the text associated to them as a tag.
Now whenever a particular radio button is selected, just get the tag which will give you the text associated with it.
String text = (String) selectedRadioButton.getTag();
Hope it helps.

Related

Android -get radio button id based on value

I want to highlight right and wrong option when user clicks a button after checking an radio button. If that option is right, highlight. Else highlight right option.
Is there any way to get radio button id in a group based on its value? Or Do I need to use switch case?
I searched enough but not able to find out what I need.
Edit
I have simple layout which contains one question, 4 choices, one button. User check a radio button and click the check button. If user selects wrong option, highlight the correct option. I know what is correct option by value.
choice1, choice2, choice3, choice4 are four radio buttons. User checks choice3. But choice2 is correct. How do I select choice2 by value in this radio group.
group.getRadioButtonId("choice2")
Anything similar to this?
You could iterate through the children of your RadioGroup to get the required one:
int count = radioGroup.getChildCount();
for (int i = 0 ; i < count; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.getText().equals("choice2")) {
int id = button.getId(); // the ID you're looking for
}
}
You Can check like this
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int rbId = group.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
switch (group.getId()) {
case R.id.radiogroupID:
if (rb.getText().toString().equalsIgnoreCase("right")) {
// your logic
} else {
//your logic
}
}
}
you can use these line. its working for me
int checkedId = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(checkedId);
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
First check which option is true. hear choice 2 OK. set by default is checked true and than check user checked value . if user select other option than display message and pass true option we already checked true
Create an int array with all the ids of the radiobutton
int[] rb_IDs=new int[]{R.id.rb1,R.id.rb2,R.id.rb3};
Then inside your button click :
RadioGroup rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i=0;i<rb_IDs.length;i++)
{
RadioButton rb=(RadioButton)findViewById(rb_IDs[i]);
if (rb.getText().toString().equals("YOUR CORRECT ANSWER")&&!rb.isChecked())
{
//
//Do your thing
//
//ID of the correct answer Radiobutton is
int id=rb_IDs[i];
//HighLighting the answer
rb.setBackgroundColor(Color.parseColor("#00ff00"));
break;
}
}
}
});

How to get all of unchecked radio buttons in android

I have 16 Radio Group in my layout and i have 40 Radio Button . I want to get which Radio Button is unchecked in Radio Groups. I want to know how can i know is there any unchecked Radio Button in my layout thanks
You should probably group all of your buttons like so:
RadioGroup rg = (RadioGroup) findViewById(R.id.my_radio_group);
List<RadioButton> radioButtonsList = new ArrayList<>();
for(int i = 0; i < rg.getChildCount(); ++i) {
RadioButton b = rg.getChildAt(i);
if(b.isChecked()) radioButtonsList.add(b);
}
Do it for all of your groups and you'll have all your unchecked buttons in a list.
Also you can use:
int checkedRadioButtonId = rg.getCheckedRadioButtonId()
to get only checked button's id.
ArrayList<RadioGroup> radioGroupList = new ArrayList<RadioGroup>();
RadioGroup group1 = (RadioGroup)findViewById(...);
RadioGroup group2 = (RadioGroup)findViewById(...);
.
.
RadioGroup group16 = (RadioGroup)findViewById(...);
radioGroupList.add(group1);
radioGroupList.add(group2);
.
.
radioGroupList.add(group16);
and later you can check which is checked or not with this
for(RadioGroup radioButtonGroup:RadioGroupList){
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
}
or if it's the RadioButtons you are interested in then add them in an ArrayList the same way and loop in that list like this
for(RadioButton radioButton:radioButtonList){
boolean isChecked = radioButton.isChecked();
}
You can check the state of radio buttons by using the isChecked() method.
This question has already been answered here:
How to check if "Radiobutton" is checked?

RadioGroup.clearCheck() not working in case of dynamically created radio buttons

In my app,i am creating radio buttons dynamically and want to uncheck all other radio buttons when one of them is checked.For this purpose,i am using RadioGroup.clearCheck() but it is not working at all.This is the code:
for (int i=0; i<files.length; i++)
{
rbi = new RadioButton(context);
rb1 = new RadioGroup(context);
rb1.addView(rbi);
nameOfFile = files[i].getName();
rbi.setText(nameOfFile);
ll.addView(rb1);
rbi.setOnClickListener(
new RadioButton.OnClickListener()
{
#Override
public void onClick(View v)
{
rb1.clearCheck();
rbi.setChecked(true);
}
Please help me.Even the alternate solutions for achieving the goal will be welcomed.Thanks in advance.
You create a lot of RadioGroups with just 1 RadioButton inside. That is probably not what you want. A RadioGroup needs to contain several RadioButtons so you can select an active button inside the list. See code below
// create 1 RadioGroup, add it to the layout
RadioGroup rg = new RadioGroup(context);
ll.addView(rg);
// add several RadioButtons to the RadioGroup
for (int i=0; i < files.length; i++) {
String nameOfFile = files[i].getName();
RadioButton rb = new RadioButton(context);
rb.setId(i); // assign an id
rb.setText(nameOfFile);
rg.addView(rb); // add to group
}
// do something when user checks a button
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// user selected files[checkedId].getName();
}
});
Did you try (with System.out.println("test");) or something, if it even gets into the clearing part? Would test that first.
This is what zapl means
rb1.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rb1,
int checkedId) {
Log.v("Selected", "New radio item selected: " + checkedId);
}
});
if that works, then you can try this:
if (rbi.isChecked()){
rb1.clearCheck();
rbi.setChecked(true);
}

how to remove radio button items programmatically

In xml layout I have RadioGroup, Button1, Button2. When user clicks on button1, several radio buttons are programmatically created in RadioGroup (total amount of radio buttons may differ (pocet = count of radio buttons to be created).
final RadioButton[] rb = new RadioButton[pocet];
RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);
radiobuttonCount++;
for(int i=0; i<pocet; i++){
rb[i] = new RadioButton(this);
rb[i].setText("Radio Button " + radiobuttonCount);
rb[i].setId(radiobuttonCount+i);
rb[i].setBackgroundResource(R.drawable.button_green);
rg.addView(rb[i]);
}
What I try to do is this: When user selects xy item from RadioGroup, I'll pass selected value to textview and remove all radioButtons.
For deleting purpose I use:
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
boolean isChecked = checkedRadioButton.isChecked();
if (isChecked)
{
RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);
for (int i=0; i< rg.getChildCount(); i++){
rg.removeViewAt(i);
}
}
Problem is that this sometimes works well, but sometimes first radio button remains undeleted.
P.S.
Later I want to add button2 that will feed radiogroup with different items and different radio buttons amount. That's why I need to remove all radio buttons after user does selection.
Its really easy, you just do this:
rg.removeAllViews();
because i worked with the for loop but it didn't remove all the RadioButtons.
have fun :)
My first guess is that this portion of code is bad:
for (int i=0; i< rg.getChildCount(); i++){
rg.removeViewAt(i);
}
you can't run over one view's children while removing child at the same time
(rg.getChildCount() will change during the run)

How to add radio buttons to radio group

I have a TableLayout and in the third column of every row I want to place a radio group.
I build the RadioButtons like this:
rg = (RadioGroup) findViewById(R.id.radioGroup1);
for (int k = 0; k < size; k++) {
rb[k] = new RadioButton(context);
rg.addView(rb[k]);
}
However this cause my app to crash, any ideas?
You are building a primitive array with the length of megethos, but your loop uses the length size. If megethos and size are different values this can cause many different types of errors... But all of this redundant since a RadioGroup keeps this array up to date for you.
I would try something like this:
RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton button;
for(int i = 0; i < 3; i++) {
button = new RadioButton(this);
button.setText("Button " + i);
group.addView(button);
}
And when you want to reference a button at index:
group.getChildAt(index);
Also please always post your logcat errors, it tells us exactly what went wrong and where to look. Otherwise we have to guess like this.
Update
The error is because you are trying to add the same button to two different layouts:
tr[k].addView(rb[k]);
rg.addView(rb[k]);
a view can only have one parent. As far as I know you cannot break a RadioGroup apart into multiple views without a lot of customization first. However a ListView already has the built-in feature setChoiceMode() that behaves like a RadioGroup:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setAdapter(adapter);
You can easily adapt simple_list_item_checked to display the SSID and signal strength. Hope that helps. (If you wait long enough imran khan might cut & paste my answer with graphical change, then claim it as his own again.)
I have created one demo app in which I have added Radio buttons dynamically and also handled click events.
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup2;
ArrayList<String> buttonNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup2 = (RadioGroup) findViewById(R.id.radioGroup2);
buttonNames = new ArrayList<>();
buttonNames.add("No Tip");
buttonNames.add("10%");
buttonNames.add("20%");
buttonNames.add("30%");
radioGroup2.setWeightSum(Float.parseFloat(buttonNames.size() + ""));
radioGroup2.setBackgroundColor(Color.BLUE);
for (int i = 0; i < buttonNames.size(); ++i) {
RadioButton radioButton = new RadioButton(this);
radioButton.setId(i);
RadioGroup.LayoutParams childParam1 = new RadioGroup.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f);
childParam1.setMarginEnd(2);
radioButton.setGravity(Gravity.CENTER);
radioButton.setLayoutParams(childParam1);
radioButton.setBackground(null);
radioButton.setText(buttonNames.get(i));
radioButton.setTextColor(Color.BLUE);
radioButton.setBackgroundColor(Color.WHITE);
radioButton.setButtonDrawable(null);
if (buttonNames.get(i).equals("20%")) {
radioButton.setChecked(true);
radioButton.setBackgroundColor(Color.BLUE);
radioButton.setTextColor(Color.WHITE);
}
radioGroup2.addView(radioButton, childParam1);
}
radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i1) {
RadioButton button = null;
for (int i = 0; i < buttonNames.size(); ++i) {
if (i1 == i) {
button = (RadioButton) findViewById(i1);
button.setChecked(true);
button.setBackgroundColor(Color.BLUE);
button.setTextColor(Color.WHITE);
Toast.makeText(getApplicationContext(), button.getText() + " checked", Toast.LENGTH_SHORT).show();
} else {
button = (RadioButton) findViewById(i);
button.setChecked(false);
button.setBackgroundColor(Color.WHITE);
button.setTextColor(Color.BLUE);
}
}
}
});
}
}

Categories

Resources