单选按钮圈未渲染-可能是由于上下文

时间:2018-11-24 13:07:30

标签: java android xml

我根据Firebase中的数据创建程序化单选按钮。单选按钮的数量可以是2-4:

    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((getContext())));
        RadioButton radioButton = mPollAnswerArrayList.get(indexCreated);
        radioButton.setTag(indexCreated);
        radioButton.setText(answer.getAnswer().toString());
        radioButton.setTextColor(getResources().getColor(R.color.black));
        //TODO: Investigate if this line is necessary
        radioButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.radio_button_answer_text_size));

        //TODO: Determne which type of RadioButton to use for consistency
        if (Build.VERSION.SDK_INT >= 21) {
        //                radioButton.setButtonTintMode(PorterDuff.Mode.DARKEN);
        } else {
            //TODO: Is this necessary? What happens?
        //                radioButton.setButtonDrawable(R.drawable.black_ring);
        }

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

我注意到在API 23上,由于某些原因这些按钮没有出现。我仍然可以单击以实现所需的结果,但是该按钮实际上不是UI并未呈现的按钮:

enter image description here

enter image description here

编辑:这可能与我的Context参数有关,不确定它是否与API相关,但是我没有正确传递上下文。请注意,该代码在Fragment中。从.getContext()更改为.getApplicationContext()时,我注意到了差异。还可能我没有使用支持库单选按钮吗?

mPollAnswerArrayList.add((indexCreated), new RadioButton((getContext())));

1 个答案:

答案 0 :(得分: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();