Search code examples
androidandroid-relativelayout

How to match the widths of two TextViews in android using xml alone


I have two string resources. However I don't know which of the two strings would produce the wider TextView. I want to create two TextViews, one on top of the other, one using the text of the first resource, and the other using the text of the second resource. I want the TextViews to be the same width, but no wider than necessary.

I can achieve this. I use a layout resource that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
    >
    <TextView
        android:id="@+id/green_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:textSize="18sp"
        android:padding="5dp"
        android:background="@android:color/white"
        android:textColor="@android:color/holo_green_dark"
        android:text="@string/green_text"
        />
    <TextView
        android:id="@+id/blue_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/green_text_view"
        android:layout_alignLeft="@id/green_text_view"
        android:gravity="center"
        android:textSize="18sp"
        android:padding="5dp"
        android:background="@android:color/white"
        android:textColor="@android:color/holo_blue_dark"
        android:text="@string/blue_text"
        />
</RelativeLayout>

and I make the widths match in onCreate(), by using code like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView greenTextView = (TextView) findViewById(R.id.green_text_view);
    TextView blueTextView = (TextView) findViewById(R.id.blue_text_view);
    greenTextView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    blueTextView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    int maxWidth = Math.max(greenTextView.getMeasuredWidth(), blueTextView.getMeasuredWidth());
    greenTextView.setWidth(maxWidth);
    blueTextView.setWidth(maxWidth);
}

It works. The TextViews are aligned and centred whichever TextView is naturally wider.

My question: is it possible to do this using xml alone? Any help would be greatly appreciated.


Solution

  • That seems impossible. As you don't know which one will be naturally wider, RelativeLayout (and you) can't tell the dependency between the two. If you accidentally use layout_align*attribute to align the wider View B with the normal one, the content of B will be clipped.