2013-05-12 59 views

回答

0

该程序块显示如何以编程方式创建RadioButton组。

希望它能帮助你。

public class RadioGroupActivity extends Activity { 
    protected static final String TAG = "RadioGroupActivity"; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.radiogroup); 

     RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp); 

     int checkedRadioButtonID = radGrp.getCheckedRadioButtonId(); 

     radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
      public void onCheckedChanged(RadioGroup arg0, int id) { 
       switch(id) { 
       case -1: 
        Log.v(TAG, "Choices cleared!"); 
        break; 
       case R.id.chRBtn: 
        Log.v(TAG, "Chose Chicken"); 
        break; 
       case R.id.fishRBtn: 
        Log.v(TAG, "Chose Fish"); 
        break; 
       case R.id.stkRBtn: 
        Log.v(TAG, "Chose Steak"); 
        break; 
       default: 
        Log.v(TAG, "Huh?"); 
        break; 
       } 
      }}); 
    } 

}

0

在这里你有它...

ln = (LinearLayout)findViewById(R.id.Linear_layout); // Assuming linearLayout is your parent layout 

     RadioGroup rg = new RadioGroup(context); // create the RadioGroup 
    rg.setLayoutParams(new LinearLayout.LayoutParams(
          LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f)); 

         cg_Value = new String{“item 1”, “item 2”, “item 3”}; 
         rb = new RadioButton[cg_Value.length]; 
         rg.setOrientation(RadioGroup.HORIZONTAL);// horizontal or vertical depends on requirement 
         for (int l = 0; l < cg_Value.length; l++) { 
          rb[l] = new RadioButton(context); 
          rg.addView(rb[l]); // the RadioButtons are added to 
                 // the radioGroup instead of the 
                 // layout 
          rb[l].setTextColor(Color.BLACK); 
          rb[l].setText(cg_Value[l]); 
          rb[l].setTextSize(14); 
         } 
         //rb[1].setChecked(true); 

ln.addView(rg); 

希望这会有所帮助