findViewById not working for an include?

I have an include like:

<include
    android:id="@+id/placeHolder"
    layout="@layout/test" />

The include layout looks like (test.xml):

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/outer"
    ... >

    <ImageView
        android:id="@+id/inner"
        ... />
</FrameLayout>

I can't seem to find the inner ImageView with id="inner" at runtime:

ImageView iv = (ImageView)findViewById(R.id.inner);
if (iv == null) {
    Log.e(TAG, "Not found!");
}

Should I be able to find it? It seems like since it's using an "include", the normal findViewById method does not work.

---------- Update ----------------

So I can find the id assigned to the include:

View view = findViewById(R.id.placeHolder); // ok

but I can't find any of its children by id like:

view.findViewById(R.id.outer); // nope
view.findViewById(R.id.inner); // nope

same as the original if I try searching for them directly like:

findViewById(R.id.outer); // nope
findViewById(R.id.inner); // nope

Do ids just get stripped off of elements at runtime maybe?

Thanks


Solution 1:

Try retrieving the <include /> and then searching within that

Make sure your root has the same ID as the root element in the included XML file.. ex

<include
    android:id="@+id/outer"
    layout="@layout/test" />

Then retrieve your "inner" content using:

FrameLayout outer = (FrameLayout)findViewById(R.id.outer);

ImageView iv = (ImageView)outer.findViewById(R.id.inner);
if (iv == null) {
    Log.e(TAG, "Not found!");
}

Solution 2:

I just wanted to add to this for future Googlers, I had kind of the opposite problem where the root layout of the included xml (in this case outer), was null when calling findViewById(), but the children of outer were not null.

The problem was solved for me by removing the id property of the include 'view' (in this case placeHolder). When that was gone, I could find outer but it's id :)

If you need a an id assigned to the include item, I think it's better to wrap it in another viewgroup.