简体   繁体   中英

How can I access my Activity's instance variables from within an AlertDialog's 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;

        } 

    }

}

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM