gpt4 book ai didi

java - 仅在选中时打印多个复选框名称

转载 作者:行者123 更新时间:2023-12-02 03:35:46 25 4
gpt4 key购买 nike

我有复选框列表,每次单击显示消息按钮时都想打印它们的名字。该消息显示为 android.widget.Toast。如果选中多个复选框,我想将它们全部打印在一个字符串中。我使用 switch-case 语句来确定单击哪些复选框,并在这种情况下将新名称添加到结果字符串中。

case R.id.cbox_choclate_syrup:
if (checked)
tag = tag + "chocolate syrup ";
break;

enter image description here

我在这里遇到了问题。结果字符串是在类的开头创建的,在第一次点击按钮后,第二次点击它包含相同的项目名称,即使它们没有被检查。我可以添加更多项目,但结果字符串永远不会重置。

public void tosMessage(String message){
Context context = getApplicationContext();
CharSequence msg = message;
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, msg, duration);
toast.show();
// resetting the result string.
tag = "Toppings: ";
}

如上所示,我尝试在属于按钮的 onClick 方法末尾重置结果字符串。在这种情况下,即使我没有取消选中,之前选中的项目也会在第二次单击时被删除。

public class MainActivity extends AppCompatActivity {

public static String tag = "Toppings: ";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void onCheckboxClicked(View view) {

// is the view now checked.
boolean checked = ((CheckBox) view).isChecked();

// check which checkbox is checked?
switch (view.getId()){
case R.id.cbox_choclate_syrup:
if (checked)
tag = tag + "chocolate syrup ";
break;
case R.id.cbox_sprinkles:
if (checked)
tag = tag + "sprinkles ";
break;
case R.id.cbox_crushed_nuts:
if (checked)
tag = tag + "crushed nuts ";
break;
case R.id.cbox_cherries:
if (checked)
tag = tag + "cherries ";
break;
case R.id.cbox_orio_cookie_crumbles:
if (checked)
tag = tag + "orio cookie crumbles ";
break;
}
}

public void tosMessage(String message){
Context context = getApplicationContext();
CharSequence msg = message;
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, msg, duration);
toast.show();
tag = "Toppings: ";
}

public void showMsg(View view) {
tosMessage(tag);
}
}

我希望每次单击按钮时仅打印且专门检查的项目名称。请帮我找到解决方案。

最佳答案

view.getId() 等于其中一种情况时,该 case 中的语句运行,并且 break 终止整个 switch-case 因此应用程序不会检查其他 CkeckBox。因此,您必须将 switch 语句替换为 if-else-if

int id= view.getId();
if(id == R.id.cbox_choclate_syrup){
if(checked)
tag = tag + "chocolate syrup ";
}
else if(id == R.id.cbox_sprinkles){
if(checked)
tag = tag + "sprinkles ";
}
else if(id == R.id.cbox_crushed_nuts){
if(checked)
tag = tag + "crushed nuts ";
}
else if(id == R.id.cbox_cherries){
if(checked)
tag = tag + "cherries ";
}
else if(id == R.id.cbox_orio_cookie_crumbles){
if(checked)
tag = tag + "orio cookie crumbles ";
}

注意:删除break语句不起作用。

关于java - 仅在选中时打印多个复选框名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56862886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com