Programmatically-added RadioButtons refuse to obey LayoutParams weighting

前端 未结 3 1055
余生分开走
余生分开走 2020-12-30 01:17

I\'m trying to create a RadioGroup within an Android layout where the child RadioButtons are stretched to evenly fill the entire width of the

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 01:48

    I ran into this issue too, I used the RadioGroup.LayoutParams with weight defined. However I also found once I'd created programatically the buttons weren't responding to touch so set clickable and enabled to true and that fixed things.

      private RadioButton createMyTypeRadioButton(MyType type){
    
        //create using this constructor to use some of the style definitions
        RadioButton radio = new RadioButton(this, null, R.style.MyRadioStyle);
    
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
        radio.setLayoutParams(layoutParams);
        radio.setGravity(Gravity.CENTER);
    
        //tag used by the setOnCheckedChangeListener to link the radio button with mytype object
        radio.setTag(type.getId());
    
        //enforce enabled and clickable status otherwise they ignore clicks
        radio.setClickable(true);
        radio.setEnabled(true);
    
        radio.setText(type.getTitle());
    
    
        return radio;
    }
    
    private void updateMyTypesUi() {
    
        //populate RadioGroup with permitted my types
        for (int i = 0; i < myTypes.size(); i++) {
            MyType type = myTypes.get(i);           
            RadioButton radioButton = createSwapTypeRadioButton(type);
            myRadioGrp.addView(radioButton);
    
        }
    
        myRadioGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checkedType = (RadioButton) group.findViewById(checkedId);              
                String idOfMyTypeChecked = (String) checkedType.getTag();
                //do something with idOfMyTypeChecked
            }
        });
    }
    

提交回复
热议问题