Search code examples
androidandroid-layoutandroid-widget

Why does findViewById(...) return null?


findViewById is returning null for me on an ImageView widget. There is no error and nothing in logcat that indicates what is going on. The id's match and other image views are being set properly. Java and xml are linked by the class tag in xml pointing to the class defined in java which is a descendant of RelativeLayout.

I tried changing the name of R.id.more_icon1 and that didn't work. Tried cleaning and that didn't work. Used debugger to see that it really does just move on past and when it returns mMoreIcon == null.

What's wierd is that the other ImageView's work just fine.

Anyone seen this before or have any ideas?

Java Code: Class is a descendant of RelativeLayout

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    mText1 = (TextView) findViewById(R.id.text1);
    mText2 = (TextView) findViewById(R.id.text2);
    mIcon1 = (ImageView) findViewById(R.id.icon1);
    mIcon2 = (ImageView) findViewById(R.id.icon2);
    // mMoreIcon is the one that gets set as null. mIcon1 and mIcon2 work just fine.
    mMoreIcon = (ImageView) findViewById(R.id.more_icon1);

}

XML Code:

<ImageView android:id="@+id/icon1"
    style="@style/SuggestionIcon1"
    android:scaleType="centerInside"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
/>

<!--     This is the icon that is being returned as null -->
<ImageView android:id="@+id/more_icon1"
    style="@style/MoreIcon2"
    android:scaleType="centerInside"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:visibility="gone" />

<ImageView android:id="@+id/icon2"
    style="@style/SuggestionIcon2"
    android:scaleType="centerInside"
    android:layout_toLeftOf="@id/more_icon1"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:visibility="gone" />

Thanks


Solution

  • I had a similar issue and my problem was that findviewbyid only find child views. If the view is a sibling you'd have to call it from the parent. The activity should be able to find it.