I have an Activity with a ListView which I’ve added a listener (setOnItemClickListener).
When I’m inside this method from the listener above mentioned:
public void onItemClick(AdapterView<?> parent, View view, int pos, long id )
In order to have access to the Activity, I’ve done this:
MyActivity host = (MyActivity) parent.getContext();
From host variable, I have access to all MyActivity methods and attributes (which aren’t static), but I can’t access to the MyActivity.this reference.
Could someone explain me why? Thanks
MyActivity.thiswould reference the instance of the “outer” MyActivity class when your code ran in an inner class. — Does it? If so, why would you need thehostvariable?Update: It only just occured to me that you may be missing the fact that everything you would access via
MyActivity.thisfrom within an inner class, you can access viahostin your specific setup.Update: You seem to have a wrong understanding of the meaning of
this. Originally, it stands for this object, i.e. the class in which your code runs.With the additional notation
Class.this, Java enables you to access the instance of the outer class of your code, but only from an inner class.In the following example,
Class.thisworks:Also, in the following example,
Class.thisdoes not work. The reason is simply that the system cannot know whether there is an Instance of class A and which one of the possibly many instances of class A you want to refer to.Once again, please be aware that you asked a question without providing the necessary information to answer it specifically, so it can only be answered in general and it looks like you have a wrong understanding about inner classes and the
Class.thisnotation.