How to add radio button dynamically as per the given number of counts?
Please find below the code, I have created an 'EditText' and a 'Button' in the xml layout. Input a number in the 'EditText' and click the Button , The same no. of radio buttons will be added in the Layout.
This is your ActivityMain
public class ActivityMain extends AppCompatActivity implements View.OnClickListener {
EditText mEtNumOfRadioBtns;
Button mBtnAdd;
String TAG = "TestActivity";
RadioGroup mRgAllButtons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
mEtNumOfRadioBtns = findViewById(R.id.et_no);
mBtnAdd = findViewById(R.id.btn);
mRgAllButtons = findViewById(R.id.radiogroup);
//
mBtnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(mEtNumOfRadioBtns.getText().toString().trim());
addRadioButtons(number);
}
});
}
public void addRadioButtons(int number) {
mRgAllButtons.setOrientation(LinearLayout.HORIZONTAL);
//
for (int i = 1; i <= number; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(View.generateViewId());
rdbtn.setText("Radio " + rdbtn.getId());
rdbtn.setOnClickListener(this);
mRgAllButtons.addView(rdbtn);
}
}
@Override
public void onClick(View v) {
Log.d(TAG, " Name " + ((RadioButton)v).getText() +" Id is "+v.getId());
}
}
And here is your layout file with name 'activity_main'
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical" />
<LinearLayout
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Enter no."
android:inputType="number"
android:id="@+id/et_no"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Add Radio btn"
android:id="@+id/btn"/>
</LinearLayout>
</RelativeLayout>
Add N Number of Radio buttons in Android
Well, This can be done through a simple for loop
class FragmentQues : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragmentques_layout, container, false)
}
@SuppressLint("ResourceType")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val value = 2;
// If you have custom text for each button you have to define them in a list
val textList = listOf("No", "Yes")
for(i in 0 until value){
// Create RadioButton programmatically
val radioButton = RadioButton(activity)
radioButton.layoutParams= LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
radioButton.setText(textList[i])
radioButton.id = i
profile_radio_group.addView(radioButton)
}
profile_radio_group.setOnCheckedChangeListener { group, checkedId ->
if (checkedId ==1){
// Some code
}else{
// Some code
}
}
}
- Note that the text has to be passed as an array to match your needs as described in the code
Generating a number of radio buttons dynamically in aspx
Seems like you're mixing ASP.NET & ASP.NET MVC
If you're Using ASP.NET MVC:
<% for (int i = 0; i < Model.PossibleAnswers.Count; ++i) { %>
{
<label>
<%= Html.RadioButtonFor(m => m.PossibleAnswers[i].TheAnswer, m.PossibleAnswers[i]..ID) m.PossibleAnswers[i].TheAnswer %>
</label>
<% } %>
If you are using ASP.NET:
Use RadioButtonList
for this purpose. It is better suited for such operations.
One way could be to declare the control in your aspx file and then on PageLoad
event you can add items/bind it to the collection.
IMHO Binding is a generally a better option.
Binding Example:
http://asp-net-example.blogspot.com/2009/03/how-data-bind-radiobuttonlist-on-button.html
Adding Example:
protected override void OnInit(EventArgs e)
{
RadioButtonList1.Items.AddRange(GetItems());
base.OnInit(e);
}
private ListItem[] GetItems()
{
return new ListItem[] {
new ListItem("Item 1", "1"),
new ListItem("Item 2", "2"),
new ListItem("Item 3", "3"),
new ListItem("Item 4", "4")
});
}
How to dynamically count no. of selected radio buttons and show them inside a div
you can set an event listener on inputs for change event. give an id to h1
that you want to change and set its text using .text()
. $('input[type="radio"]:checked').length
will give number of checked radio buttons. something like this:
$('input[type="radio"]').change(function(){ $('#result').text("the no. of checkboxes selected are: " + $('input[type="radio"]:checked').length);})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><h1>first part</h1> <input type ="radio" name="hope1" value=""> <input type ="radio" name="hope2" value=""> <input type ="radio" name="hope3" value=""><h2>second part</h2> <input type ="radio" name="hope1" value=""> <input type ="radio" name="hope2" value=""> <input type ="radio" name="hope3" value=""></div>
<div><h1 id='result'> the no. of checkboxes selected are:"it should be displayed here"</h1> </div>
Can I create dynamically RadioGroup with RadioButtons inside it (w/o xml)?
Something like this:
....
RadioGroup group = new RadioGroup(this);
group.setOrientation(RadioGroup.HORIZONTAL);
RadioButton btn1 = new RadioButton(this);
btn1.setText("BTN1");
group.addView(btn1);
RadioButton btn2 = new RadioButton(this);
group.addView(btn2);
btn2.setText("BTN2");
....
RadioButton btnN = new RadioButton(this);
group.addView(btnN);
btnN.setText("BTNN");
yourLayout.addView(group);
....
Dynamically add Radio Button Labels - JavaScript
The label element might not be inserted by the next line itself. It is better to do
myLabel.innerHTML = 'labelMessage';
As you have the element already in a variable.
Creating Radio Button dynamically
-(void)radioSelected:(UIButton*)sender {
int tag =sender.tag;
NSLog(@"buttonSelectedtag:%d",tag);
sender.selected = !sender.selected;
self.yourButton = sender;
for (UIButton *i in self.view.subviews){
if([i isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton *)i;
if(btn.tag == previouslySelectedTag){ //hold previouslySelectedTag, selectedTag globally
// Write your code. Change Button Image
}
}
}
previouslySelectedTag = sender.tag;
}
Related Topics
How to Implement Ssl Certificate Pinning While Using React Native
Just Upgraded My Os X to Yosemite, Android Device Chooser Not Showing Device - What to Do
Android Gcm Basic Implementation
Getting Gradle Error "Could Not Reserve Enough Space for Object Heap" Constantly in Intellij Idea
How to Keep a Button as Pressed After Clicking on It
Using Audiotrack in Android to Play a Wav File
Android Studio and Android.Support.V4.App.Fragment: Cannot Resolve Symbol
Custom Filtering Arrayadapter in Listview
Camera Preview Stretched on Few Android Devices
Simulate Killing of Activity in Emulator
How to Execute Background Task When Android App Is Closed/Set to Background
How to Look-Up a Contact's Name from Their Phone Number on Android
Selecting Contact from Autocomplete Textview
Shouldoverrideurlloading in Webview for Android Not Running
Can't Create New Kotlin Project After Updating to Android Studio 4.2