单选按钮以编程方式设置页边距和对齐方式

时间:2018-11-27 01:26:03

标签: android xml radio-button

我正在使用RadioButtons设置RadioGroup,它们都基于Firebase中的数据动态填充。我将参数设置如下:

 mParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    mParams.setMargins(0,0,4,6);

然后我实例化我的RadioButton对象:

public void addRadioButtonsWithFirebaseAnswers(List<DocumentSnapshot> answers) {
        mPollAnswerArrayList = new ArrayList<RadioButton>();
        int indexCreated = 0;
        for (DocumentSnapshot answerSnapshot : answers) {
            Answer answer = answerSnapshot.toObject(Answer.class);
            mPollAnswerArrayList.add((indexCreated), new RadioButton(mContext));
            RadioButton radioButton = mPollAnswerArrayList.get(indexCreated);
            radioButton.setTag(indexCreated);
            radioButton.setText(answer.getAnswer().toString());
            radioButton.setTextColor(getResources().getColor(R.color.black));
            radioButton.setButtonDrawable(R.drawable.custom_btn_radio);
            //TODO: Investigate if this line is necessary
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.radio_button_answer_text_size));

            mPollQuestionRadioGroup.addView(radioButton, mParams);
            indexCreated++;
        }
    }

下面是它的显示方式。我想在单选按钮和文本之间添加空格。我还希望每个按钮之间有间隔。最后,如果可能的话,我希望文本以按钮为中心。

enter image description here

2 个答案:

答案 0 :(得分:1)

这很容易在按钮和文本之间添加空格:

radioButton.setText("   " + answer.getAnswer().toString());

要更改按钮之间的距离,可以执行以下操作:

LayoutParams params = new LayoutParams(
    LayoutParams.WRAP_CONTENT,      
    LayoutParams.WRAP_CONTENT
);
params.setMargins(leftMargin, topMargin, rightMargin, 15);
radioButton.setLayoutParams(params);

15是bottomMargin,您可以根据需要进行更改。我希望这会有所帮助。

答案 1 :(得分:0)

尝试一下。

LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(10, 10, 10, 10); // leftMargin, topMargin, rightMargin, buttomMargin
     RadioGroup radioGroup = new RadioGroup(getContext());
     RadioButton radioButton = new RadioButton(getContext());
     radioButton.setLayoutParams(params1);
     radioButton.setId(1);
     radioButton.setText("text");
     radioButton.setPadding(0, 5, 0, 5); // leftMargin, topMargin, rightMargin, buttomMargin
     radioGroup.addView(radioButton);

使用它来检查/选择单选按钮,

radioGroup.check(3);  

将其用于未选中的单选按钮

radioGroup.clearCheck();