I have a made a custom Button called ActionButton and I'm trying to get reference to another view that is in a parallel view hierarchy. I thought of using findViewById(int id), but I kept getting NullPointerExceptions, so I tried to get reference to the RootView via getRootView(), and from there get the view with findViewById(int id). The problem is now that getRootView instead of returning a layout or null, it returns my ActionButton that called that method.
Here is my ActionButton, where I try to get reference:
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...
}
}
And a overview of my layout.xml file:
<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>
I would really appreciate if you could explain to me why getRootView returns the view itself or could give me a hint how I can reference it any other way.
If you'll take a look at the source code of the getRootView method:
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;
}
you'll see, that the only case when this method returns itself is the case if the view has not been attached to the view hierarchy (and mAttachInfo.mRootView is not null) and it has no parent or a parent is not a View instance. Best regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With