2012-05-29 62 views
3

我有一个名为ActionButton的自定义按钮,我试图获取对并行视图层次结构中的另一个视图的引用。我想过使用findViewById(int id),但我一直收到NullPointerExceptions,所以我试图通过getRootView()获得对RootView的引用,并从那里获得与findViewById(int id)的视图。现在的问题是getRootView而不是返回布局或null,它返回我的ActionButton调用该方法。查看getRootView返回自己

这里是我的ActionButton,在那里我试图让参考:

public class ActionButton extends Button { 

    protected void onFinishInflate(){ 
     super.onFinishInflate(); 
     log(getRootView() == this) //true, what I don't understand... 
     ConnectionLayer connectionLayer = (ConnectionLayer) findViewById(R.id.connection_layer); //Returns null... 
    } 
} 

而且我layout.xml文件的概述:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" > 

     (much more xml elements) 

     <com.cae.design.reaction.ui.ActionButton 
      android:id="@+id/actionButton" 
      android:layout_width="match_parent" 
      android:layout_height="150dp" 
      android:layout_gravity="center_vertical" /> 

    </LinearLayout> 

    <com.cae.design.reaction.ui.ConnectionLayer 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/connection_layer" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 
    </com.cae.design.reaction.ui.ConnectionLayer> 

</FrameLayout> 

我真的很感激,如果你能向我解释为什么getRootView返回视图本身,或者可以给我一个提示,我可以如何以任何其他方式引用它。

回答

0

尝试拨打getParent()代替,并根据需要将结果转换为ViewGroup。然后,您可以使用getChildCount()getChildAt()访问其他子视图。

+0

不,这也行不通。当我调用'getParent'时,它返回null,所以它看起来像问题是我的ActionButton没有添加到视图层次结构。但是我认为当onFinishInflate方法被调用时,布局会完成... – Artjom

+1

嗯,可能需要在后面的调用中做你的逻辑,比如'onPreDraw'或'onAttatchedToWindow'或类似的东西。 – wsanville

2

如果你看一看的getRootView方法的源代码:

public View getRootView() { 
     if (mAttachInfo != null) { 
      final View v = mAttachInfo.mRootView; 
      if (v != null) { 
       return v; 
      } 
     } 

     View parent = this; 

     while (parent.mParent != null && parent.mParent instanceof View) { 
      parent = (View) parent.mParent; 
     } 

     return parent; 
    } 

你会看到,当这个方法返回自己的唯一情况是,如果认为还没有的情况下附加到视图层次结构(并且mAttachInfo.mRootView不为空),并且它没有父代或父代不是View实例。 此致敬礼。

0

getRootView()返回自身,因为当ActionButton完成时,如果它的父代没有。我的意思是,当您调用getRootView()时,ActionButton不会连接到LinearLayout。我这样做,当我需要一个根视图:

new Thread(new Runnable() { 

    @Override 
    public void run() 
    { 
        // wait until LinearLayout will finish inflating and this 
        // view will be connected to it 
     while(getRootView() == this) {} 
     // do your buisness now 
    } 
}).start();