java - 将值传递给回调函数

标签 java android checkbox sdk reference

我希望我的代码在复选框的选中/取消选中事件上动态执行某些操作。 我有这段代码:

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/

相关文章:

java - 字符 15 处不存在 Postgres 函数

Android:如何通过通知下拉菜单检测何时更改设置?

jquery - 无法检查 JavaScript 中的所有复选框

javascript - 在加载时为预先选中的复选框运行 ng-change 函数

javascript - 防止复选框完全勾选/检查

java - 没有通过 jsoup 获得正确的页面

java - 介意帮助第一次遇到减速带的新人吗?

java - 模拟 getActionBar() 返回 null

android - 针对 Android 优化 Canny 边缘检测器

android - 如何在选择时突出显示 GridView 项目?