0
0
Android Kotlinmobile~5 mins

Arrangement and alignment in Android Kotlin

Choose your learning style9 modes available
Introduction

Arrangement and alignment help you place items neatly on the screen. They make your app look organized and easy to use.

When you want buttons to appear side by side or stacked vertically.
When you want text or images centered on the screen.
When you want to space items evenly in a list or grid.
When you want to align items to the left, right, or center inside a container.
When you want your app layout to look good on different screen sizes.
Syntax
Android Kotlin
LinearLayout(
  android:orientation = "vertical" or "horizontal",
  android:gravity = "center" or "start" or "end",
  android:layout_gravity = "center" or "start" or "end"
)

orientation decides if items stack vertically or horizontally.

gravity aligns content inside the layout.

Examples
This stacks items vertically and centers them inside the layout.
Android Kotlin
<LinearLayout
  android:orientation="vertical"
  android:gravity="center">
  <!-- child views here -->
</LinearLayout>
This arranges items side by side aligned to the left.
Android Kotlin
<LinearLayout
  android:orientation="horizontal"
  android:gravity="start">
  <!-- child views here -->
</LinearLayout>
This stacks items vertically aligned to the right.
Android Kotlin
<LinearLayout
  android:orientation="vertical"
  android:gravity="end">
  <!-- child views here -->
</LinearLayout>
Sample App

This app creates a horizontal layout with three buttons vertically centered inside the layout. The buttons appear side by side, packed to the left.

Android Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val layout = LinearLayout(this).apply {
      orientation = LinearLayout.HORIZONTAL
      gravity = android.view.Gravity.CENTER_VERTICAL
      layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT
      )
    }

    val button1 = Button(this).apply { text = "Left" }
    val button2 = Button(this).apply { text = "Center" }
    val button3 = Button(this).apply { text = "Right" }

    layout.addView(button1)
    layout.addView(button2)
    layout.addView(button3)

    setContentView(layout)
  }
}
OutputSuccess
Important Notes

Use LinearLayout for simple horizontal or vertical arrangements.

Use gravity to align content inside the layout, and layout_gravity to align the layout itself inside its parent.

For more complex layouts, consider ConstraintLayout or GridLayout.

Summary

Arrangement controls how items are stacked or placed side by side.

Alignment controls where items appear inside their container.

Use LinearLayout with orientation and gravity for basic layout control.