我在我的活动xml中有5个复选框。我需要获取所有选中复选框的文本。
一种方法是查看checkbox1是否被选中并获取文本。
if(checkbox1.isChecked())
{ String text=checkbox1.getText().toString();}
等等,还有其他的方法。
这个过程变得相当冗长。
我能用其他方法吗?
我在我的活动xml中有5个复选框。我需要获取所有选中复选框的文本。
一种方法是查看checkbox1是否被选中并获取文本。
if(checkbox1.isChecked())
{ String text=checkbox1.getText().toString();}
等等,还有其他的方法。
这个过程变得相当冗长。
我能用其他方法吗?
You do not need to ==true
operation above so a simple if(checkbox1.isChecked())
would suffice.
Store them all in an ArrayList
so you can iterate as below:
List<CheckBox> items = new ArrayList<CheckBox>();
for (CheckBox item : items){
if(item.isChecked())
String text=item.getText().toString();
}
CheckBox[] nameString = new CheckBox[]{Array1, Array2, Array3, Array4, Array5, Array6, Array7, Array8};
for (int i=0; i<=7; i++)
{
if (nameString[i].isChecked())
{
Toast.makeText(getApplicationContext(), nameString[i].getText().toString(), Toast.LENGTH_SHORT).show();
}
}
onCheckedChanged()
或 onClick()
中简单地创建一个已选择项目的列表。If(unChecked)==>Add to List==> if(Checked) ==> Remove from list
Kotlin示例代码:
您可以创建一个事件并将同一事件绑定到所有复选框,例如
<CheckBox
android:id="@+id/chk1"
android:onClick="onCheckBoxClicked" ....
<CheckBox
android:id="@+id/chk2"
android:onClick="onCheckBoxClicked" ....
主活动:
fun onCheckBoxClicked(view:View){
view as CheckBox
if (view.isChecked){
var msg = view.text.toString()
Log.d("Checkbox", msg) //printing in log
}