[英]How can I access my Activity's instance variables from within an AlertDialog's onClickListener?
Here's a very simplified version of my Activity
: 这是我的
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;
}
}
}
When the menu button is pressed, my applications pops up an AlertDialog
. 当按下菜单按钮时,我的应用程序将弹出
AlertDialog
。 When creating the AlertDialog
and in-line onClickListener
is attached to the each of the items in the dialog. 当创建
AlertDialog
和在线onClickListener
被附接到每个对话框中的项目。 I need to access the objAdapater
variable that is defined in my Search
activity. 我需要访问在
Search
活动中定义的objAdapater
变量。 I don't have access to the search instance within my onClickListener
so I can't access it. 我无权访问
onClickListener
的搜索实例,因此无法访问它。 I have a little bit of a soup in my code with the passing of the Activity
instance everywhere. 在随处都传递
Activity
实例的情况下,我的代码有些麻烦。 Maybe I'm doing something wrong. 也许我做错了。
How would I get access to the Activity
( Search
instance) from within my onClickListener
so I can access it's methods and variables. 我如何从
onClickListener
内访问Activity
( Search
实例),以便可以访问它的方法和变量。
Thank you. 谢谢。
Using Search.this.objAdapter
to access objAdapter
from the listener should work. 使用
Search.this.objAdapter
从侦听器访问objAdapter
应该可以工作。
Search.this
refers to the current instance of Search
and allow you to access its fields and methods. Search.this
指向Search
的当前实例,并允许您访问其字段和方法。
Make your activity implement OnClickListener: 使您的活动实现OnClickListener:
public class Search extends Activity implements DialogInterface.OnClickListener { ...
Add the onclick method to your activity: 将onclick方法添加到您的活动中:
public void onClick(DialogInterface dialog, int item) {
//I need to access it from here.
}
Then pass your activity as the listener: 然后将您的活动作为侦听器传递:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(itmMenuitem.getTitle());
builder.setSingleChoiceItems(lstChoices),0, this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.