动态添加RadioButton当标题

private RadioButton createRadioButton(String name) {
        RadioButton mRadioButton = new RadioButton(this);
        RadioGroup.LayoutParams mLayoutParams = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT,1);
        mLayoutParams.setMargins(1, 0, 1, 0);
        mRadioButton.setLayoutParams(mLayoutParams);

        mRadioButton.setClickable(true);
//        mRadioButton.setButtonDrawable(this.getResources().getDrawable(R.drawable.selector_weekly_indicator));
        mRadioButton.setButtonDrawable(null);
        mRadioButton.setBackground(null);
        mRadioButton.setText(name);
        mRadioButton.setTextColor(getResources().getColorStateList(R.drawable.textcolor));
        mRadioButton.setGravity(Gravity.CENTER);
        return mRadioButton;
    }

    private void initView() {

        radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        for (int i = 0; i < 7; i++) {
            radiogroup.addView(createRadioButton("猪肉"+i));
        }

        radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.e(TAG, "onCheckedChanged: "+i );
                RadioButton childAt = (RadioButton) radioGroup.getChildAt(i - 1);
                CharSequence text = childAt.getText();
                Log.e(TAG, "onCheckedChanged: "+text );

            }
        });

    }

你可能感兴趣的:(动态添加RadioButton当标题)