问题
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