findViewById不适用于包含?

use*_*701 40 android

我有一个像:

<include
    android:id="@+id/placeHolder"
    layout="@layout/test" />
Run Code Online (Sandbox Code Playgroud)

include布局看起来像(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>
Run Code Online (Sandbox Code Playgroud)

我似乎无法在运行时找到id ="inner"的内部ImageView:

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

我应该能找到它吗?似乎因为它使用"include",正常的findViewById方法不起作用.

----------更新----------------

所以我可以找到分配给include的id:

View view = findViewById(R.id.placeHolder); // ok
Run Code Online (Sandbox Code Playgroud)

但我找不到任何一个像id的孩子:

view.findViewById(R.id.outer); // nope
view.findViewById(R.id.inner); // nope
Run Code Online (Sandbox Code Playgroud)

如果我尝试直接搜索它们,就像原来一样:

findViewById(R.id.outer); // nope
findViewById(R.id.inner); // nope
Run Code Online (Sandbox Code Playgroud)

是不是只是在运行时剥离了元素?

谢谢

dym*_*meh 72

尝试检索<include />然后在其中搜索

确保您的根与包含的XML文件中的根元素具有相同的ID

<include
    android:id="@+id/outer"
    layout="@layout/test" />
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法检索"内部"内容:

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

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

  • 试试我的最新答案.确保include的id与包含的XML文件中的root元素相同 (7认同)
  • 我只想指出确保include的id与包含的XML文件中的根元素的id相同的重要性.正如@dymmeh所说的那样.我第一次阅读答案时完全错过了这个建议,将它考虑在内是非常重要的.非常感谢您的帮助! (4认同)
  • 嘿,是的也不起作用,用它来更新问题. (3认同)
  • 如果include的id与内部的根元素相同,那么没有使用覆盖它,它将按原样膨胀.根据LayoutInflater源代码,它不会覆盖合并根元素的id - 使得重用布局大致无用,布局可以共享id并在包含时覆盖它们 (2认同)

Dan*_*son 13

我只是想为未来的Google员工添加这个,我有一个相反的问题,其中包含xml的根布局(在本例中为外部),在调用findViewById()时为null,但外部的子项不为null.

通过删除include'view' 的id属性(在本例中为placeHolder)解决了这个问题.当那个消失了,我可以找到外部,但它是id :)

如果你需要为include项目分配一个id ,我认为最好将它包装在另一个视图组中.

  • 这对我有用 - 谢谢.我做了一些挖掘和(至少在我的非碎片代码中)我发现了以下内容:如果你有一个带有id的include并想要访问包含结构的顶层,那么include id必须与包含项的顶级结构的id.这感觉不对,因为它似乎是一个重复的名称 - 它有效.另一种可行的方法是你的解决方案 - 即错过包含的名称. (5认同)