Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...