androidandroid-imageandroid-imagebutton

Why is my circular ImageButton not working?


I'm trying to create a round circular image button in Android. I don't want to use CircleImageView because its scale type is centerCrop and you can't change that. I want my scale type to be fitCenter or centerInside.

This is my code for my ImageButton:

<ImageButton
    android:id="@+id/profile_image_view"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:layout_marginTop="16dp"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:background="@drawable/circle_image_button"
    android:src="@drawable/default_profile"/>

This is my circle_image_button.xml code:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <stroke android:color="@android:color/white" android:width="2dp" />
            <size android:width="96dp" android:height="96dp"/>
        </shape>
    </item>
</selector>

When I run my app, the image is placed on top of the circle. So basically it does not scale down and fit inside of the circle. All you see is a square image. I want the image to fit inside the circle and be able to see the white stroke. How do I fix this?


Solution

  • If only scaletype is your issue I will suggest you to use ShapeableImageView, this will let you add shaped to you imageview and you can add the scaletype at your own usecase, for e.g.:

    <com.google.android.material.imageview.ShapeableImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:shapeAppearance="@style/RoundedImageViewShape"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:scaleType="centerInside"/>
    

    and style RoundedImageViewShape, can be:

    <style name="RoundedImageViewShape">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">50%</item>
    </style>