1

我正在尝试在两个特定的 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>

任何提示为什么这不起作用?生成的 textview 不显示边框或背景颜色。

谢谢!

4

1 回答 1

1

目前 ( 1.3.0)MaterialTextView不使用 aMaterialShapeDrawable并且不支持andShapeAppearanceModel属性shapeAppearance/shapeAppearanceOverlay

有关文档中支持的组件的更多信息。

但是,您可以申请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>
于 2021-03-24T16:27:10.083 回答