Android:有没有一种简单的方法可以为视图创建圆角,而不必每次都创建单独的可绘制对象?

Har*_*sha 5 android android-shapedrawable material-components material-components-android

我在互联网上浏览了各种解决方案,这使我们能够创建带有圆角的视图。它们中的大多数需要使用创建自定义视图,或者在每次我们需要圆角视图时在 xml 或九补丁中创建一个 drawable。

问题是,当我实现这样的视图时,我需要为每个这样的视图创建一个 drawable,即使两个视图除了背景颜色之外的所有东西都一样。这对我来说有点刺激,我听说 iOS 框架提供了一种创建圆角视图的好方法。任何帮助将非常感激。

编辑:除了圆角,视图和阴影的按压效果也是常用的样式。请让您的解决方案包含这些影响。

Gab*_*tti 11

随着材料零件库,你可以使用MaterialShapeDrawable绘制自定义形状

例如,TextView你可以这样做:

    <TextView
        android:id="@+id/textview"
        android:backgroundTint="@color/secondaryColor"
        ../>
Run Code Online (Sandbox Code Playgroud)

然后创建一个MaterialShapeDrawable

float radius = getResources().getDimension(R.dimen.default_corner_radius);

TextView textView = findViewById(R.id.textview);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
        .toBuilder()
        .setAllCorners(CornerFamily.ROUNDED,radius)
        .build();

MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
ViewCompat.setBackground(textView,shapeDrawable);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

用一个简单的View

<View
    android:id="@+id/line"
    android:layout_width="match_parent"
    android:layout_height="4dp"
    android:backgroundTint="@color/..."/>
Run Code Online (Sandbox Code Playgroud)

然后应用相同的MaterialShapeDrawable

View line = findViewById(R.id.line);
ViewCompat.setBackground(line,shapeDrawable);
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您还可以创建不同的角:

ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,0)
    .setBottomRightCorner(CornerFamily.ROUNDED,radius)
    .build();
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

此外,材质组件库提供的大多数组件都有一个 MaterialShapeDrawable 作为背景。
在这些情况下,只需使用类似的东西(在本例中为 MaterialCardView)。

  MaterialCardView cardView = findViewById(R.id.card);
  cardView.setShapeAppearanceModel(cardView.getShapeAppearanceModel()
        .toBuilder()
        .setBottomLeftCornerSize(...)
        .setBottomEdge(...)
        .build());
Run Code Online (Sandbox Code Playgroud)

它需要库的1.1.0版。目前1.1.0-beta02