5

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

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

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

4

3 回答 3

12

使用材料组件库,您可以使用MaterialShapeDrawable绘制自定义形状

例如,TextView你可以这样做:

    <TextView
        android:id="@+id/textview"
        android:backgroundTint="@color/secondaryColor"
        ../>

然后创建一个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);

在此处输入图像描述

用一个简单的View

<View
    android:id="@+id/line"
    android:layout_width="match_parent"
    android:layout_height="4dp"
    android:backgroundTint="@color/..."/>

然后应用相同的MaterialShapeDrawable

View line = findViewById(R.id.line);
ViewCompat.setBackground(line,shapeDrawable);

在此处输入图像描述

您还可以创建不同的角:

ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,0)
    .setBottomRightCorner(CornerFamily.ROUNDED,radius)
    .build();

在此处输入图像描述

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

  MaterialCardView cardView = findViewById(R.id.card);
  cardView.setShapeAppearanceModel(cardView.getShapeAppearanceModel()
        .toBuilder()
        .setBottomLeftCornerSize(...)
        .setBottomEdge(...)
        .build());

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

于 2019-11-26T15:57:17.650 回答
0

您可以以编程方式将 Gradient drawable 用于您的视图,并可以将该视图设置为背景

 GradientDrawable getRoundedCornerView(int shapetype,int color,float radius){
     GradientDrawable shape = new GradientDrawable();
     shape.setShape(shapetype); //GradientDrawable.RECTANGLE for rectangle
     shape.setColor(color);
     shape.setCornerRadius(radius);
retrun shape;
}
于 2019-11-26T10:53:16.170 回答
-1

如果你只想改变背景的颜色,你可以使用backgroundTint

例如:


    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/background"
        app:backgroundTint="#F00"
        />

请注意:我在app:backgroundTint这里使用,通过使用app前缀,AppCompat 视图(AppCompatImageView、AppCompatButton 等)可以读取此属性并在棒棒糖之前的 Android 设备上为背景着色,但您应该确保您使用的是 appcompat 库。

通用解决方案:

再三考虑,我想出了一个方法:您可以创建一个LayoutInflater.Factory并用您自己的自定义视图替换所有视图(imageView、TextView 等),该视图以角半径和颜色作为背景,就像 AppCompat 库一样

于 2019-11-26T08:46:37.790 回答