【问题标题】:How to keep a TextView square?如何保持 TextView 正方形?
【发布时间】:2016-06-09 21:05:41
【问题描述】:

我找到了this answer,它可以确保保留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 保持正方形(以及背景因此是一个完美的圆形?)。

【问题讨论】:

  • 子类化并覆盖 onMeasure
  • @Blackbelt 你能详细说明一下吗?我尝试对其进行子类化并覆盖onMeasure,但在读取该调用中的高度和宽度时我得到了一些奇怪的值。
  • 如果你不需要任何花哨的东西this应该这样做

标签: android layout view


【解决方案1】:

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

【讨论】:

  • 我从未使用过dimen.xml 文件,我该如何定义它?
  • values文件夹下的资源文件
  • 我知道,但是我应该如何定义一个圆形半径呢?如果宽度大于高度,只需输入padding="5sp" 仍会使其变为椭圆形。
  • 是的,你可以。我建议不要硬编码。
  • 标签内使用&lt;size android:height="20dp"android:width="20dp"/&gt;
【解决方案2】:

在 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"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多