Home > Software engineering >  Set Image View gravity right Android
Set Image View gravity right Android

Time:10-03

I am trying to make the shuffle-button (image view) to the right using gravity as picture below.

enter image description here

Here is my layout.xml

<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:layout_gravity="center"
       android:layout_weight="1"
       android:weightSum="2"
       >
       <TextView
           android:id="@ id/Loop"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:text="L"
           android:gravity="left"
           android:textSize="36sp"
           android:layout_margin="8dp"
            />

       <ImageView
           android:id="@ id/shuffle"
           android:layout_width="0dp"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:layout_margin="8dp"
           android:gravity="right"
           app:srcCompat="@drawable/ic_shuffle_black_24dp" />
   </LinearLayout>

What did I do wrong? I could move the L button fine, but not the shuffle button.

CodePudding user response:

You can achieve what you want by:

  1. Removing the layout_weight and weightSum from your LinearLayout
  2. Changing the width of the ImageView to wrap_content
  3. Changing the layout_weight of the ImageView to 0

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center">
    <TextView
        android:id="@ id/Loop"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="L"
        android:gravity="left"
        android:textSize="36sp"
        android:layout_margin="8dp" />

    <ImageView
        android:id="@ id/shuffle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_margin="8dp"
        android:gravity="right"
        app:srcCompat="@drawable/ic_shuffle_black_24dp" />
</LinearLayout>

This will allow the ImageView to take up as much space as it needs, based on the size of the src asset. The rest of the space will be utilized by the TextView.

  • Related