我根据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呈现的:


编辑:这可能与我的上下文参数有关,不确定它是否与API相关,但我没有正确传递上下文。请注意,代码在片段中。当我从.getContext()改为.getApplicationContext()时,我注意到了不同之处。还有可能我没有使用支持库单选按钮?
mPollAnswerArrayList.add((indexCreated), new RadioButton((getContext())));发布于 2018-12-01 16:19:51
这是最简单的方法。尝尝这个。
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();https://stackoverflow.com/questions/53458459
复制相似问题