我正在 Android 中开发一个类似测验的应用程序。每个问题都是一个回收器视图项目,以便我可以按顺序呈现多个问题类型。我的问题是:有没有办法像 RadioButton 组一样实现 CheckBox 组?通过 RadioButton 组,我只需调用即可添加答案(RadioButton):
RadioGroup radioGroup = view.findViewById(R.id.answer_grp);
RadioButton rb = new RadioButton("context...");
rb.setText("text");
radioGroup.addView(rb);
是否有与此类似的复选框组的实现?我是否应该使用提供的 RadioButton 组的实现并自定义 RadioButton 的布局以使其看起来像复选框?在这种情况下,最好的做法是什么?
提前非常感谢!
您可以尝试这个库https://github.com/xeoh/CheckBoxGroup
希望这有帮助!
您可以使用像
ViewGroup
这样的 LinearLayout
将 CheckBox
组合在一起,并为您的类实现 CompoundButton.OnCheckedChangeListener
来处理选中的更改事件:
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
CheckBox q1A1CheckBox;
CheckBox q1A2CheckBox;
CheckBox q1A3CheckBox;
CheckBox q1A4CheckBox;
CheckBox q2A1CheckBox;
CheckBox q2A2CheckBox;
CheckBox q2A3CheckBox;
CheckBox q2A4CheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1A1CheckBox = findViewById(R.id.main_q1_a1_checkBox);
q1A2CheckBox = findViewById(R.id.main_q1_a2_checkBox);
q1A3CheckBox = findViewById(R.id.main_q1_a3_checkBox);
q1A4CheckBox = findViewById(R.id.main_q1_a4_checkBox);
q2A1CheckBox = findViewById(R.id.main_q2_a1_checkBox);
q2A2CheckBox = findViewById(R.id.main_q2_a2_checkBox);
q2A3CheckBox = findViewById(R.id.main_q2_a3_checkBox);
q2A4CheckBox = findViewById(R.id.main_q2_a4_checkBox);
q1A1CheckBox.setOnCheckedChangeListener(this);
q1A2CheckBox.setOnCheckedChangeListener(this);
q1A3CheckBox.setOnCheckedChangeListener(this);
q1A4CheckBox.setOnCheckedChangeListener(this);
q2A1CheckBox.setOnCheckedChangeListener(this);
q2A2CheckBox.setOnCheckedChangeListener(this);
q2A3CheckBox.setOnCheckedChangeListener(this);
q2A4CheckBox.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int currentCheckBoxGroupId = ((LinearLayout) compoundButton.getParent()).getId();
switch (currentCheckBoxGroupId) {
case R.id.main_q1_linearLayout:
Toast.makeText(this, "Question one", Toast.LENGTH_SHORT).show();
//do whatever you want
break;
case R.id.main_q2_linearLayout:
Toast.makeText(this, "Question two", Toast.LENGTH_SHORT).show();
//do whatever you want
break;
}
}
}
您可以使用RadioGroup和RadioButton。 我们需要将这两个属性添加到RadioButton
android:button="@null"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"