MaterialTextView shapeAppearanceOverlay 不工作

MaterialTextView shapeAppearanceOverlay not working

我正在尝试在两个特定的 MaterialTextView 上实现带有彩色背景的简单圆角布局。代码如下:

 <com.google.android.material.textview.MaterialTextView
    android:id="@+id/lblStartTime"
    style="@style/customTimeRangePickerStyle"
    android:layout_width="68dp"
    android:layout_height="wrap_content"
    android:padding="8dp"
    android:textAlignment="center"
    android:textSize="18sp" />

<style name="customTimeRangePickerStyle" parent="">
    <item name="shapeAppearanceOverlay">@style/customTimeRangePickerDay</item>
</style>

<style name="customTimeRangePickerDay" parent="">

    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">4dp</item>

    <item name="strokeWidth">1dp</item>
    <item name="strokeColor">@color/Cor2</item>

    <item name="android:background">@color/fieldBackground</item>
</style>

为什么这不起作用的任何提示?生成的文本视图不显示边框和背景颜色。

谢谢!

目前 (1.3.0) MaterialTextView 不使用 MaterialShapeDrawable 并且 不支持 ShapeAppearanceModelshapeAppearance/shapeAppearanceOverlay 个属性。

有关 the doc 中受支持组件的更多信息。

但是您可以申请 MaterialShapeDrawable:

      <com.google.android.material.textview.MaterialTextView
          android:id="@+id/textview"
          android:paddingLeft="8dp"
          android:gravity="center_vertical"
          android:backgroundTint="@color/white"
          android:text="Text"
          />

和:

val radius = resources.getDimension(R.dimen.default_corner_radius)

val textView = findViewById<TextView>(R.id.textview)
val shapeAppearanceModel = ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED, radius)
    .build()

val shapeDrawable = MaterialShapeDrawable(shapeAppearanceModel)
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.red600));
ViewCompat.setBackground(textView, shapeDrawable)

您还可以使用主题中定义的叠加层构建 ShapeAppearanceModel。只需在上面的代码中使用:

 val shapeAppearanceModel =
            ShapeAppearanceModel.builder( context,
                    R.style.ShapeAppearance_MaterialComponents_SmallComponent,
                    R.style.shapeAppearanceOverlay)
            .build()

与:

<style name="shapeAppearanceOverlay">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">xxx</item>
</style>