Pass to object java class is embedded as parameter

I am creating an Android application that looks like a list, and in the list view, is a click listener containing the onItemClick method. So I have something like this:

public class myList extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { getListView().setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* Do something*/ } } } 

This usually works fine. However, many times I find that I too need a preform of an application that uses an external class as a context. so i used:

 parent.getContext(); 

to do this, but I would like to know is this a bad idea? I really can't call:

 super 

because it is not really a subclass, just inline. So is there a better way, or is it considered smart? Also, if this is the right way, what should I do if the built-in method does not have a parameter to get the outer class?

Thanks.

+4
source share
2 answers

If I understand your question correctly, you want to call an outer class from an anonymous inner class, right? To do this, use the following syntax:

 myList.this.getContext(); 

from the onItemClick method of onItemClick anonymous inner class. This is a special syntax defined for an inner class to access an instance of an outer class that contains it.

+3
source

Inside an anonymous inner class, you can get an outer class handle with EnclosingClass.this. For information see here . Long and short, you can use myList.this.getContext () in your onItemClick () element.

+2
source

Source: https://habr.com/ru/post/1307312/


All Articles