已将视图通知添加到父项? [英] Notification on View added to parent?

查看:70
本文介绍了已将视图通知添加到父项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Android中动态构建View时,必须通过调用

When I build a View in Android dynamically I have to add it to a "parent" ViewGroup by calling

myLinearLayout.addView(myView);

我知道我可以通过优秀的

I know that I can supervise the ViewGroup for any children to be added via the excellent onHierarchyChangeListener, but in my case I need the feedback in the View itself. Therefore my question is:

是否可以建立像View.onAddedToParent()回调或侦听器之类的东西?

Is there something like a View.onAddedToParent() callback or a listener that I can build on?

为了使事情非常清楚:我希望视图能够自己处理所有事情,我知道我可以在父"中捕获事件,然后将有关情况的通知通知给视图,但这是不需要.我只能更改视图

To make things very clear: I want the view to handle everything on its own, I am aware of the fact that I could catch the event in the "parent" and then notify the view about things, but this is not desired here. I can only alter the view

我刚刚找到 onAttachStateChangeListener 可以在大多数情况下工作,但是我想知道这是否真的是正确的解决方案.我在想View可能也可以从一个ViewGroup传递到另一个而又不会与窗口分离.因此,即使我愿意,我也不会收到任何活动.如果您有见识,可以请您详细说明一下吗?

I just found onAttachStateChangeListener and it would seem to work for most situations, but I'm wondering if this is really the correct solution. I'm thinking a View might just as well be passed on from one ViewGroup to another without being detached from the window. So I would not receive an event even though I want to. Could you please elaborate on this if you have insight?

预先感谢

推荐答案

您可以创建自定义视图,并在其onAttachedToWindow中完成您的工作

You can create custom view and do your stuff in its 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();
   }
}

如果要确保您的自定义视图添加到所需的正确视图组中,则

If you want to ensure that your customview added to correct viewgroup which you want

@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();          
    }

}

这篇关于已将视图通知添加到父项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆