访问包含的xml布局视图
我需要访问包含在另一个b.xml布局中的x.xml布局中的视图。 例如, 这是A.XML访问包含的xml布局视图
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/xyz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XYZ" />
</RelativeLayout>
而且,在B.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include
android:id="@+id/a_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
layout="@layout/a" />
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/xyz"
android:text="Show me below xyz" />
</RelativeLayout>
我必须这样做,在XML代码,因为如果我在Java中做到这一点就必须经过setContentView()然后设置TextView'label'的LayoutParams不会生效。
我想,每个人都明白我想问什么。等待好的回复。
谢谢大家。
右边的图片是我想要实现的,剩下的就是我用当前的代码得到的。
在B.XML,你应该纠正:
android:layout_below="@id/xyz"
到
android:layout_below="@id/a_layout"
然后你就可以在你的代码中使用它(在这里,我把它放在onCreate):
setContentView(R.layout.b);
((Button)findViewById(R.id.xyz)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((TextView)findViewById(R.id.label)).setText("clicked on XYZ button");
}
});
这没有工作,无论在b.xml中看到包括布局有android:layout_height =“fill_parent”所以它的自然,TextView将不会显示。 – 2012-04-10 08:20:47
@Trickster哦,我忘了重新检查它 - 它必须有android:layout_height =“wrap_content”非常感谢。 – 2012-04-10 08:26:29
问题不在于访问包含的布局的View
,而是因为您无法实现这种布局“重叠”。让我解释一下:如果您在a.xml
的按钮下方添加更多视图,然后尝试在按钮正下方的b.xml
中放置一些视图,那么它将使b.xml
的视图与a.xml
重叠,但是尚未实施Android(但?)。所以,你可以做的唯一的事情就是把@作为@HoàngToản的建议。
P.S.您可能会观察到与此a
+ b
布局组合相同的行为:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/xyz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XYZ" />
</RelativeLayout>
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/xyz"
android:text="Show me below xyz" />
</RelativeLayout>
实际上,我的应用中的布局与示例非常不同,这就是为什么我无法将两者结合在一起。 这些只是两个布局,但在我的项目中,有15个布局,其中包含a.xml,而a.xml不是简单的例子,它是每个活动的标题。 – 2012-04-10 13:08:31
正如我所指出的,你不能用当前的Android SDK获得如此复杂的结构 - 'a' +'b'组合说明它(没有'include'元素,但仍然是相同的行为,请参阅?)。 – 2012-04-10 13:28:27
您想问什么? – 2012-04-10 07:48:32
如果我已经猜到了,那么通过它的id来访问它:'findViewById(R.id.label)' – 2012-04-10 07:50:03
你说得对,我可以使用findViewById(R.id.label)来访问它。但我不能这样做android:layout_below =“@ id/xyz” – 2012-04-10 07:59:09