我有一个像:
<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)
Dan*_*son 13
我只是想为未来的Google员工添加这个,我有一个相反的问题,其中包含xml的根布局(在本例中为外部),在调用findViewById()时为null,但外部的子项不为null.
通过删除include
'view' 的id属性(在本例中为placeHolder)解决了这个问题.当那个消失了,我可以找到外部,但它是id :)
如果你需要为include
项目分配一个id ,我认为最好将它包装在另一个视图组中.