MaterialTextView shapeAppearanceOverlay not working

2k views Asked by At

I am trying to achieve a simple rounded corner layout with a colored background on two specific MaterialTextViews. Codes are below:

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

Any tips why this is not working? The resulting textview shows no borders nor background color.

Thanks!

1

There are 1 answers

3
Gabriele Mariotti On BEST ANSWER

Currently (1.3.0) the MaterialTextView doesn't use a MaterialShapeDrawable and doesn't support the ShapeAppearanceModel and shapeAppearance/shapeAppearanceOverlay attributes.

More info a about the supported components in the doc.

However you can apply a 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"
          />

and:

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)

enter image description here

You can also build the ShapeAppearanceModel using an overlay defined in the theme. Just use in the code above:

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

with:

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