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

前端 未结 4 803
心在旅途
心在旅途 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:30

    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'

    
    
    
        
    
        
    
            
    
            

提交回复
热议问题