How to add radio button dynamically as per the given number of counts?

前端 未结 4 802
心在旅途
心在旅途 2020-12-01 03:28

I have tried this code..It will display three radio buttons in a single row when the emulator starts. But I need a button event for this. i.e; if I click the button, it shou

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 04:09

    This is the way to do this:

        RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);        
        int buttons = 5;
        for (int i = 1; i <= buttons ; i++) {
            RadioButton rbn = new RadioButton(this);
            rbn.setId(View.generateViewId());
            rbn.setText("RadioButton" + i);
            rgp.addView(rbn);
        }
    

    But what if you need to do this horizontally, just add the orientation (the default value is vertical) with setOrientation() method:

        RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
        rgp.setOrientation(LinearLayout.HORIZONTAL);
        int buttons = 5;
        for (int i = 1; i <= buttons; i++) {
            RadioButton rbn = new RadioButton(this);
            rbn.setId(View.generateViewId());
            rbn.setText("RadioButton" + i);
            rbn.setLayoutParams(params);
            rgp.addView(rbn);
        }
    


    This is the complete code:

    first of all defining inside our Layout the RadioGroup:

    
    
    
        
    
    

    The code into the MainActivity:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //Defining 5 buttons.
            int buttons = 5;
            AppCompatRadioButton[] rb = new AppCompatRadioButton[buttons];
    
            RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
            rgp.setOrientation(LinearLayout.HORIZONTAL);
    
            for (int i = 1; i <= buttons; i++) {
                RadioButton rbn = new RadioButton(this);
                rbn.setId(View.generateViewId());
                rbn.setText("RadioButton" + i);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
                rbn.setLayoutParams(params);
                rgp.addView(rbn);
            }
    
        }
    }
    

提交回复
热议问题