Search code examples
androidxmlandroid-layoutviewandroid-imageview

Fix sizes for Imageview in Android


I have a LinearLayout with a list of six horizontal buttons in a column.

Each one has this structure:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_menu_charge" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/view_top_up_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:fontFamily="@font/montserrat_bold"
        android:gravity="center_vertical"
        android:text="@string/menu_pay_charge"
        android:textColor="@color/black"
        app:drawableEndCompat="@drawable/ic_arrow_right_small_black" />
</LinearLayout>

The problem is that each list element has its own size and I can't get a perfect column

How can I set a fixed size for each ImageView (without increasing the drawable size)?


Solution

  • You need to give the ImageView a fixed width, e.g. :

      <ImageView
            android:layout_width="64dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ic_menu_charge" />
    

    Or, you can use layout_weight, e.g. :

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">
    
        <ImageView
            android:layout_width="0dp"
            android:layout_weight="0.5"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/ic_menu_charge" />
    
        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/view_top_up_button"
            android:layout_width="0dp"
            android:layout_weight="1.5"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:fontFamily="@font/montserrat_bold"
            android:gravity="center_vertical"
            android:text="@string/menu_pay_charge"
            android:textColor="@color/black"
            app:drawableEndCompat="@drawable/ic_arrow_right_small_black" />
    </LinearLayout>