Make component width independent from text length

21 views Asked by At

How to make TextView's to be same width in TableRow even text in one of the views is much bigger?

    <TableRow
        android:layout_weight="1"
        android:gravity="center"
        >

        <TextView
            android:layout_width="match_parent"
            android:text="Temperature"
            android:gravity="center"
            ></TextView>

        <TextView
            android:layout_width="match_parent"
            android:text="Temperatureccccccccccccccccccccccccc"
            android:gravity="center"
            ></TextView>


    </TableRow>

enter image description here

1

There are 1 answers

0
Pawan Harariya On

You can set the width of your TextView to some fixed value. If you don't want the additional text to go to next line limit the number of lines using maxLines attribute.

NOTE: Be careful when you use fixed-width. The text size can change based on device settings irrespective of the text size you specify, so the text may not be visible completely if your text view has fixed size, and user's device settings use a large text size.

<TextView
    android:layout_width="150dp"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:textSize="22sp"
    android:maxLines="1"
    android:padding="10dp"
    android:text="Temperatureccccccc" />

Sample Output:

Without maxLines attribute

Output 1

With maxLines attribute

Output 2

If you want to take the space equally use layout_weight property. It divides available space equally among two text views. Make sure to set the layout_width to 0dp.

<TableRow
            android:id="@+id/tableRow4"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:text="Temperature" />

            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:text="Temperaturecccccffffffffffffffcc" />
        </TableRow>

Sample Output:

enter image description here