Search code examples
androidxmlandroid-linearlayout

How do I right justify a TextView in a Linear Layout?


I am trying to get the TextView, "tv_amount" to stay on the right side of the screen. I have tried using android:gravity="right" but that hasn't been working for me. Anyone have any suggestions?

Image of emulator running this code:

image of emulator running this code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="40sp"
        android:layout_height="40sp"
        android:background="@drawable/circle_border"
        android:padding="6sp"
        android:layout_marginLeft="6dp"
        android:src="@drawable/food"/>

    <TextView
        android:id="@+id/tv_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginStart="12dp"
        android:text="Yummy Pizza"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="12dp"
        android:gravity="end"
        android:text="$25"
        android:textSize="25sp" />

</LinearLayout>

I am expecting the transaction or "tv_amount" to stay be right justified so that end of the number is staying towards the right side of the screen.

I tried using :

android:layout_weight="0"
android:layout_gravity="end"
android:gravity="right" 

but these don't seem to work obviously. I am a beginner when it comes to android development and can't seem to find any answers that have helped anywhere else. They all say to use android:gravity or some other alternative. Maybe there is something in my code that doesn't allow that.


Solution

  • I am dumb. The issue wasn't with the code in my individual recycler view layout code. It was with my activity_main.xml. I set the recycler_view width to "wrap_content" when it should have been "match_parent." Rookie mistake.