gpt4 book ai didi

java - 如何从 AlertDialog onClickListener 中访问我的 Activity 实例变量?

转载 作者:行者123 更新时间:2023-12-01 17:29:53 24 4
gpt4 key购买 nike

这是我的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com