开发者

Pass in the object a java class is embedded in as a parameter

I'm building an android application, which has a list view, and in th开发者_如何学JAVAe list view, a click listener, containing an 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*/
        }
    }
}

Normally, this works fine. However, many times I find myself needing too preform an application using the outer class as a context. thusfar, I've used:

parent.getContext();

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

super

because it's not really a subclass, just an embedded one. So is there any better way, or is that considered cosure? Also, if it is the right way, what should I do if the embedded method doesn't have a parameter to get the outside class?

Thank you.


If I'm understanding your question correctly, you want to call the outer class from within the anonymous inner class, right? To do so, use the following syntax:

myList.this.getContext();

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


Within an anonymous inner class you can get the handle of the outer class with EnclosingClass.this. For info see here. Long and short of it is you can use myList.this.getContext() in your onItemClick() ect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜