我有一个名为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
返回视图本身,或者可以给我一个提示,我可以如何以任何其他方式引用它。
不,这也行不通。当我调用'getParent'时,它返回null,所以它看起来像问题是我的ActionButton没有添加到视图层次结构。但是我认为当onFinishInflate方法被调用时,布局会完成... – Artjom
嗯,可能需要在后面的调用中做你的逻辑,比如'onPreDraw'或'onAttatchedToWindow'或类似的东西。 – wsanville