我有一个需要检测何时将其附加到其父 View 的 View 。
在ViewGroup
中,我有OnHierarchyChangeListener
,它使我知道何时添加/删除 subview ,但是我需要相反的事情。
最佳答案
您可以创建自定义 View ,并在其onAttachedToWindow中完成您的工作
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Log.d("CustomView", "onAttachedToWindow called for " + getId());
Toast.makeText(getContext(), "added", 1000).show();
}
}
[编辑1]
您可以确保将您的customview添加到所需的正确 View 组中
@Override
protected void onAttachedToWindow() {
// TODO Auto-generated method stub
super.onAttachedToWindow();
if(((View)getParent()).getId()== R.id.relativelayout2)
{
Log.d("CustomView","onAttachedToWindow called for " + getId());
Toast.makeText(context, "added", 1000).show();
}
}