具有不同拐角半径的CardView

Jua*_*nje 4 android android-layout material-design android-cardview material-components-android

我有以下CardView,并且我想为卡中的每个角设置不同的半径。是否可以通过XML或以编程方式更改它们?提前致谢。

<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    app:cardCornerRadius="0dp"
    app:cardElevation="0dp">
</android.support.v7.widget.CardView>
Run Code Online (Sandbox Code Playgroud)

编辑 正如阿维纳什(Avinash)所建议的那样,我正在寻找此lib github.com/captain-miao/OptionRoundCardview的行为,但使用默认的CardView项目。如果无法单独更改它,则此lib是一个不错的方法。

Gab*_*tti 8

它要求官方MaterialCardView(扩展了androidx.cardview.widget.CardView)和版本1.1.0中的材料组件库

将以下内容添加到您的布局中MaterialCardView

    <com.google.android.material.card.MaterialCardView
        style="@style/CustomCardViewStyle"
        ...>

    </com.google.android.material.card.MaterialCardView>
Run Code Online (Sandbox Code Playgroud)

定义一个继承物料卡样式的自定义样式(例如Widget.MaterialComponents.CardView),并使用shapeAppearanceOverlay属性:

  <style name="CustomCardViewStyle" parent="@style/Widget.MaterialComponents.CardView">
     <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay_card_custom_corners</item>
  </style>


  <style name="ShapeAppearanceOverlay_card_custom_corners" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">4dp</item>
    <item name="cornerSizeTopLeft">8dp</item>
    <item name="cornerSizeBottomRight">16dp</item>
    <item name="cornerSizeBottomLeft">0dp</item>
  </style>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您也可以通过编程实现它。
只需ShapeAppearanceModel对卡的角落应用自定义即可。
就像是:

float radius = getResources().getDimension(R.dimen.my_corner_radius);
cardView.setShapeAppearanceModel(
  cardView.getShapeAppearanceModel()
      .toBuilder()
      .setTopLeftCorner(CornerFamily.ROUNDED,..)
      .setTopRightCorner(CornerFamily.ROUNDED,..)
      .setBottomRightCorner(CornerFamily.ROUNDED,radius)
      .setBottomLeftCornerSize(0)
      .build());
Run Code Online (Sandbox Code Playgroud)

注意:它需要库的版本1.1.0。目前:

implementation 'com.google.android.material:material:1.1.0-beta01'
Run Code Online (Sandbox Code Playgroud)