如何访问从AlertDialog的onClickListener内我的活动的实例变量? [英] How can I access my Activity's instance variables from within an AlertDialog's onClickListener?

查看:409
本文介绍了如何访问从AlertDialog的onClickListener内我的活动的实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的活动的一个非常简化的版本:

Here's a very simplified version of my 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;

        } 

    }

}

在菜单按钮pssed $ P $,我的应用程序弹出一个 AlertDialog 。创建当 AlertDialog 和在线 onClickListener 连接到每一个对话框中的项目。我需要访问在我的搜索活动定义的 objAdapater 变量。我没有在我的 onClickListener 进入搜索实例,所以我不能访问它。我有一汤一点点在我的code与活动实例的传球无处不在。也许我做错了什么。

When the menu button is pressed, my applications pops up an AlertDialog. When creating the AlertDialog and in-line onClickListener is attached to the each of the items in the dialog. I need to access the objAdapater variable that is defined in my Search activity. I don't have access to the search instance within my onClickListener so I can't access it. I have a little bit of a soup in my code with the passing of the Activity instance everywhere. Maybe I'm doing something wrong.

我怎么会从内部访问该活动搜索实例)我的 onClickListener 这样我就可以访问它的方法和变量。

How would I get access to the Activity (Search instance) from within my onClickListener so I can access it's methods and variables.

感谢您。

推荐答案

使用 Search.this.objAdapter 访问 objAdapter 从听者应该工作。

Using Search.this.objAdapter to access objAdapter from the listener should work.

Search.this 搜索的当前实例并允许您访问其​​属性和方法。

Search.this refers to the current instance of Search and allow you to access its fields and methods.

这篇关于如何访问从AlertDialog的onClickListener内我的活动的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆