问题
I need to access the view present in a.xml layout included in another b.xml layout. For example, This is a.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>
And, in 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>
I have to do it in xml code, because if I do it in Java it must be after setContentView() and then setting LayoutParams of TextView 'label' wont take effect.
I guess, everyone understand what I am trying to ask. Waiting for good replies.
Thanks all.
Image on the right is what I am trying to achieve and left one is what I am getting with the current code.
回答1:
In b.xml, you should correct:
android:layout_below="@id/xyz"
to
android:layout_below="@id/a_layout"
And then you can use it in your code (Here I place it in 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");
}
});
回答2:
The problem is not in accessing the View
of included layout, but in the fact that you cannot achieve this layouts "overlapping". Let me explain: if you add some more views below the button in your a.xml
and then try to place some view in your b.xml
just below the button then it would make the views from b.xml
overlap views from a.xml
, however this has not been implemented in Android (yet?). So, the only thing you can do is to put android:layout_below="@id/a_layout"
as @Hoàng Toản suggested.
P.S. You may observe same behavior with this a
+ b
layouts combination:
<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>
来源:https://stackoverflow.com/questions/10084869/access-view-of-included-xml-layout