4

I found this answer, which makes sure the aspect ratio is preserved of the an ImageView.

How would I be able to do that with a TextView with a background drawable? I have this TextView:

       <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:padding="5dp"
            android:layout_margin="5dp"
            android:text="1"
            android:textColor="@color/white"
            android:id="@+id/tvCount"
            android:background="@drawable/textview_notify"
            android:layout_column="2"
            android:layout_gravity="right|top"/>

and this is my background drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <!-- The fill color -->
    <solid android:color="@color/red" />
    <!-- Just to add a border -->
    <stroke
        android:color="@color/white"
        android:width="2dp"
        />
</shape>

How to make sure the TextView stays square (and the background thus a perfect circle?).

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 1
    subclass it, and override onMeasure – Blackbelt Feb 26 '16 at 15:14
  • @Blackbelt could you elaborate on that? I tried subclassing it and overriding `onMeasure`, but I get some strange values when reading height and width I get in that call. – Bart Friederichs Feb 26 '16 at 15:56
  • If you don't need anything fancy [this](http://stackoverflow.com/questions/25770142/how-to-set-relativelayout-height-equal-to-its-width) should do it – Blackbelt Feb 26 '16 at 19:13

2 Answers2

1

Use android:gravity="center" and android:padding="@dimen/circle_radius. Define circle_radius dimen in dimens.xml file.

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103
1

Use app:layout_constraintDimensionRatio="1:1" in TextView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:text="1"
    android:textColor="@color/white"
    android:id="@+id/tvCount"
    android:background="@drawable/textview_notify"
    android:layout_column="2"
    android:layout_gravity="right|top"
    app:layout_constraintDimensionRatio="1:1"/>