java 在自定义视图中获取上下文?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7456190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:03:03  来源:igfitidea点击:

Getting the context inside a custom view?

javaandroid

提问by soren.qvist

I have made a small custom view component:

我制作了一个小的自定义视图组件:

public class ActionBar extends RelativeLayout
{

    public ActionBar(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        // .. custom logic here
    }

    private class homeButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            // how do i get the context here?
        }

    }

}

Every ActionBar component comes with a home-button, so I thought it would be appropriate to put it's onClickListener inside the view definition itself. The button should return the user to the main activity when clicked, but I need a Context in order to start activities. Can I create a local reference to the context passed in the constructor, without running into a mess of memory leaks?

每个 ActionBar 组件都带有一个主页按钮,所以我认为将它的 onClickListener 放在视图定义本身中是合适的。单击该按钮时,应将用户返回到主活动,但我需要一个 Context 才能开始活动。我可以创建对构造函数中传递的上下文的本地引用,而不会遇到一团糟的内存泄漏吗?

回答by Noel

The view has a method to get the context. See the android API for getContext().

视图有一个获取上下文的方法。请参阅getContext()的 android API 。