如何让TextView保持正方形?

4
我找到了这个答案,它确保了ImageView的纵横比被保留。

那么如果我想要一个带背景的TextView同样实现这个效果该怎么做呢?我有以下的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"/>

这是我的背景可绘制对象:

<?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>

如何确保TextView保持正方形(因此背景是一个完美的圆形)?

1
子类化它,并重写 onMeasure 方法。 - Blackbelt
@Blackbelt,你能详细说明一下吗?我尝试了子类化并覆盖 onMeasure 方法,但在读取高度和宽度时我得到了一些奇怪的值。 - Bart Friederichs
如果您不需要任何花哨的东西,这个链接应该可以解决问题:http://stackoverflow.com/questions/25770142/how-to-set-relativelayout-height-equal-to-its-width - Blackbelt
2个回答

1
使用 android:gravity="center"android:padding="@dimen/circle_radius。在 dimens.xml 文件中定义 circle_radius dimen。

我从未使用过 dimen.xml 文件,我该如何定义它? - Bart Friederichs
这是位于values文件夹下的资源文件。 - Malwinder Singh
我知道,但是我该怎么在那里定义一个圆形半径呢? 如果宽度大于高度,仅仅放置 "padding =“ 5sp”" 仍然会使其成为椭圆形。 - Bart Friederichs
是的,你可以做到。我建议不要硬编码它。 - Malwinder Singh
您要将文本放在单行中吗? - Malwinder Singh
显示剩余3条评论

1
在TextView中使用app:layout_constraintDimensionRatio="1:1"
<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"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接