这是我的Activity
的非常简化的版本:
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
。创建 AlertDialog
时,内联 onClickListener
会附加到对话框中的每个项目。我需要访问在我的 Search
Activity 中定义的 objAdapater
变量。我无权访问 onClickListener
中的搜索实例,因此无法访问它。我的代码中有一点麻烦,到处都传递 Activity
实例。也许我做错了什么。
如何从我的 onClickListener
中访问 Activity
(Search
实例),以便我可以访问它的方法和变量。
谢谢。
最佳答案
使用 Search.this.objAdapter
从监听器访问 objAdapter
应该可以。
Search.this
引用 Search
的当前实例,并允许您访问其字段和方法。
关于java - 如何从 AlertDialog onClickListener 中访问我的 Activity 实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157561/