How can I access my Activity's instance variables from within an AlertDialog's onClickListener?

不羁的心 提交于 2020-01-06 19:42:51

问题


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;

        } 

    }

}

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.

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

Thank you.


回答1:


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

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




回答2:


Make your activity implement OnClickListener:

public class Search  extends Activity implements DialogInterface.OnClickListener { ...

Add the onclick method to your activity:

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);


来源:https://stackoverflow.com/questions/12157561/how-can-i-access-my-activitys-instance-variables-from-within-an-alertdialogs-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!