Search code examples
androidxmlandroid-layoutandroid-lint

What is an alternative to this XML layout (Lint Warning)


Alright here it is, this layout will give you 3 images that are all of equal width, that width being as wide as the longest text on the 3 textviews.

They are equal width because they match_parent and the parent is wrap_content to the largest TextView.

The 3 text views are centered on the background with equals space on the left and right.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0000FF"
    android:gravity="center" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

      <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:background="#FF0000"
         android:drawableLeft="@drawable/ic_launcher"
         android:text="view 1"/>

      <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:background="#FF0000"
         android:drawableLeft="@drawable/ic_launcher"
         android:text="view 2"/>

      <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:background="#FF0000"
         android:drawableLeft="@drawable/ic_launcher" 
         android:text="view 3 longer text"/>

  </LinearLayout>
</LinearLayout>

Like so:

Preview

The problem is Lint is giving a warning that the inner LinearLayout is useless. (Which it isn't because it's what makes the inner textviews become all the same width.

Lint error

Can anyone produce the same layout but without the lint warning?


Solution

  • <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    
      <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="view 1"/>
    
      <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="view 2"/>
    
      <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" 
         android:text="view 3 longer text"/>
    </LinearLayout>
    

    This gives me similar results, without any error from Lint. I have removed the drawable tags from the code because i didnt have your drawables to use. Just add them. The only problem here is that you cant put a background in the LinearLayout tag. You will have to create a custom theme for your activity, which is quite easy as you can set an existing theme as a parent, and just change the background value... more on themes here