我做了一个小的自定义 View 组件:
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?
}
}
}
每个 ActionBar 组件都带有一个主页按钮,所以我认为将它的 onClickListener 放在 View 定义本身中是合适的。单击该按钮应使用户返回主 Activity ,但我需要一个上下文才能开始 Activity 。我可以创建对构造函数中传递的上下文的本地引用,而不会遇到内存泄漏问题吗?
最佳答案
View 有一个获取上下文的方法。查看 getContext() 的 android API .
关于java - 在自定义 View 中获取上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7456190/