我希望我的代码在复选框的选中/取消选中事件上动态执行某些操作。 我有这段代码:
checkConfidentiality.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked==true)
new AlertDialog.Builder(this).setTitle("Argh").setMessage("YEEEEEEEE").setNeutralButton("Close", null).show();
else
new AlertDialog.Builder(this).setTitle("Argh").setMessage("NOOOOOOOO").setNeutralButton("Close", null).show();
}
});
在这种特殊情况下,我在 AllertDialog 声明中收到一个错误,当然是因为在回调函数中“this”变量没有任何意义。 问题是,如何将变量(父作用域的“this”或任何其他变量)传递给回调函数? 谢谢!
最佳答案
YourClassName.this
应该可以解决问题。
或者您应该编写自定义类。例如
private class MyOnCheckedChangeListener implement CompoundButton.OnCheckedChangeListener {
private Context context;
public MyOnCheckedChangeListener (Context context) {
this.context = context;
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
并像这样使用它:
checkConfidentiality.setOnCheckedChangeListener(new MyOnCheckedChangeListener(this));
检查错别字
关于java - 将值传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16280971/