Saturday, September 24, 2016

Dynamic Radio Button Android

simple tutorial for dynamic Radio button in Android. Copy paste below code and enjoy.


1)MainActivity.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.manish.dynamicspinner;
 
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
 String countryName[] = { "India", "Pakistan", "China", "Nepal",
   "Bangladesh" };
 
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 
  LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
  for (int k = 1; k <= 20; k++) {
   //create text button
   TextView title = new TextView(this);
   title.setText("Question Number:" + k);
   title.setTextColor(Color.BLUE);
   mLinearLayout.addView(title);
   // create radio button
   final RadioButton[] rb = new RadioButton[5];
   RadioGroup rg = new RadioGroup(this);
   rg.setOrientation(RadioGroup.VERTICAL);
   for (int i = 0; i < 5; i++) {
    rb[i] = new RadioButton(this);
    rg.addView(rb[i]);
    rb[i].setText(countryName[i]);
 
   }
   mLinearLayout.addView(rg);
  }
 }
}
2)activity_main.xml
?
1
2
3
4
5
<!--?xml version="1.0" encoding="utf-8"?-->
<scrollview xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <linearlayout android:id="@+id/linear1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
    </linearlayout>
</scrollview>

No comments:

Post a Comment