androidlayoutandroid-constraintlayoutconstraint-layout-chains

center 5 items packed in linear layout


I have 5 items.

I want to center all of them horizontally and make them packed to each other.

I know in constraint layout I would create a horizontal chain and app:layout_constraintHorizontal_chainStyle=”packed”

But is it possible to do with LinearLayout? how?

here is my try:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    tools:showIn="@layout/activity_main">


  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:text="AAAAAAAAAAAAAAAAAAAAAAA" />

  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="DOT" />

  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_weight="1"



      android:text="BBB" />


</LinearLayout>

but it's not packed in the middle:

enter image description here


Solution

  • Use android:gravity="center" in your LinearLayout.

    You have to put the textviews into another linealayout

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="horizontal"
        tools:context=".MainActivity"
        android:gravity="center"
        android:layout_gravity="center">
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="AAAAAAAAAAAAAAAAAAAAAAA" />
    
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="DOT" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="BBB" />
    
        </LinearLayout>
    
    </LinearLayout>
    

    enter image description here