动态添加radiogroup

private LinearLayout layout; //布局 , 可以在xml布局中获得

 private RadioGroup group ; //点选按钮组

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        

        layout = new LinearLayout(this); //实例化布局对象

        

        group = new RadioGroup(this); //实例化单选按钮组

        

        //添加单选按钮

        for(int i = 0 ; i < 5 ; i++){

         RadioButton radio = new RadioButton(this);

         radio.setText("radio" + i);

         group.addView(radio);

        }

        

        //将单选按钮组添加到布局中

        layout.addView(group);

        

        this.setContentView(layout);

    } 

可以把单选按钮组放在 ScrollView中 ,这样的话 , 多出的部分可以滚动查看了。

添加RadioButton到RadioGroup中

  1. RadioGroup group;  
  2. for(int i=0; i<10; i++)  
  3. {  
  4.     RadioButton tempButton = new RadioButton(this);  
  5.     tempButton.setBackgroundResource(R.drawable.xxx);   // 设置RadioButton的背景图片  
  6.     tempButton.setButtonDrawable(R.drawable.xxx);           // 设置按钮的样式  
  7.     tempButton.setPadding(80, 0, 0, 0);                 // 设置文字距离按钮四周的距离   
  8.     tempButton.setText("按钮 " + i);  
  9.     group.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
  10. }  
  1. 2、为RadioGroup添加事件处理,可以得到当前选择的RadioButton
  1. group.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  2.       
  3.     @Override  
  4.     public void onCheckedChanged(RadioGroup group, int checkedId) {  
  5.         // TODO Auto-generated method stub  
  6.         RadioButton tempButton = (RadioButton)findViewById(checkedId); // 通过RadioGroup的findViewById方法,找到ID为checkedID的RadioButton  
  7.         // 以下就可以对这个RadioButton进行处理了  
  8.     }  
  9. });  
原文地址:https://www.cnblogs.com/manmanlu/p/3830957.html