user291701 user291701 - 4 months ago 24
Android Question

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

Answer Source

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!");
}