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

sor*_*ist 13 java android

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

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?
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

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

Noe*_*oel 29

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

  • 谢谢!有时答案只是盯着你. (4认同)