Java 如何访问我的活动';从AlertDialog';谁是你的听众?

Java 如何访问我的活动';从AlertDialog';谁是你的听众?,java,android,scope,instances,Java,Android,Scope,Instances,这是我的活动的一个非常简化的版本: public class Search extends Activity { //I need to access this. public SearchResultsAdapter objAdapter; public boolean onOptionsItemSelected(MenuItem itmMenuitem) { if (itmMenuitem.getItemId() == R.id.group) {

这是我的
活动的一个非常简化的版本

public class Search extends Activity {

    //I need to access this.
    public SearchResultsAdapter objAdapter;

    public boolean onOptionsItemSelected(MenuItem itmMenuitem) {


      if (itmMenuitem.getItemId() == R.id.group) {

          final CharSequence[] items = {"Red", "Green", "Blue"};

          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setTitle(itmMenuitem.getTitle());

          builder.setSingleChoiceItems(lstChoices),
              0, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                  //I need to access it from here.
                }

              });

          AlertDialog alert = builder.create();
          alert.show();

          return true;

        } 

    }

}
按下菜单按钮时,我的应用程序会弹出一个
警报对话框
。创建
AlertDialog
和内嵌
onClickListener
时,会将其附加到对话框中的每个项目。我需要访问在我的
Search
活动中定义的
objAdapater
变量。我无法访问我的
onClickListener
中的搜索实例,因此无法访问它。随着
Activity
实例的到处传递,我的代码中有了一点小麻烦。也许我做错了什么

如何从我的
onClickListener
中访问
活动(
Search
实例),以便访问它的方法和变量


谢谢。

让您的活动实现以下功能:

public class Search  extends Activity implements DialogInterface.OnClickListener { ...
将onclick方法添加到活动中:

public void onClick(DialogInterface dialog, int item) {
     //I need to access it from here.
}
然后将您的活动作为侦听器传递:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(itmMenuitem.getTitle());

builder.setSingleChoiceItems(lstChoices),0, this);

使您的活动实现OnClickListener:

public class Search  extends Activity implements DialogInterface.OnClickListener { ...
将onclick方法添加到活动中:

public void onClick(DialogInterface dialog, int item) {
     //I need to access it from here.
}
然后将您的活动作为侦听器传递:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(itmMenuitem.getTitle());

builder.setSingleChoiceItems(lstChoices),0, this);

使用
Search.this.objAdapter
从侦听器访问
objAdapter
应该可以工作


Search。此
引用
Search
的当前实例,并允许您访问其字段和方法。

使用
Search。此.objAdapter
从侦听器访问
objAdapter
应该有效

Search。此
引用
Search
的当前实例,允许您访问其字段和方法