I'm looking for some insights into the layout system. Is anyone aware of a method in the Android layout system that allows peer View
elements (meaning Views grouped together in the same container) to match their height and width attributes without creating an interstitial container just to govern their sizes?
For example: A layout has two TextView
elements. The first should always wrap width to its text content, but the second should match the width of the first. A solution that WORKS is this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
However, I had to create a special container for both views to ensure they both match the width of whatever text is in the first; adding unnecessary complexity to the hierarchy. What I would love to know is if there is a layout attribute I could use to do something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textTwo"
android:layout_widthMatchPeer="@id/textOne" <!-- An attribute like this -->
android:layout_height="wrap_content"
android:layout_below="@id/textOne" />
</RelativeLayout>
Creating a hard dimension as the width is defeating the purpose of letting the primary element wrap. Is there a technique someone is aware of, or an attribute I've missed, to accomplish this? Could be in any standard layout, I just chose RelativeLayout
as an example.
A开发者_StackOverflow社区dditionally, what if the elements are not located near each other?
Cheers.
I think the RelativeLayout
class can do what you want:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textTwo"
android:layout_alignLeft="@id/textOne"
android:layout_alignRight="@id/textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textOne" />
</RelativeLayout>
since the views are in a relatve layout, use android:layout_below="id/firsttv" android:layout_alignLeft="id/firsttv" and android:layout_alightRight="id/firsttv"
精彩评论