Ami*_*Sen 6 android android-layout material-design android-cardview material-components-android
我在我的 android 应用程序中使用材料设计,通常用于更改卡角的半径,我使用 app:cardCornerRadius,但这会更改卡的所有四个角。我想更改卡片的任何特定角落。我不想只使用 drawable 来改变角落。有没有办法通过xml或以编程方式。
<com.google.android.material.card.MaterialCardView
style="@style/Widget.MaterialComponents.CardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorWhite"
app:cardCornerRadius="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="16dp" android:layout_marginEnd="16dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="match_parent">
Run Code Online (Sandbox Code Playgroud)
Gab*_*tti 10
使用 Material 组件 1.1.0 版本,您可以使用属性自定义组件的形状shapeAppearanceOverlay
。
您可以在视图或样式中使用它。
<com.google.android.material.card.MaterialCardView
.....
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MaterialCardView.Cut">
Run Code Online (Sandbox Code Playgroud)
然后定义你最喜欢的形状:
<style name="ShapeAppearanceOverlay.MaterialCardView.Cut" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSizeTopRight">0dp</item>
<item name="cornerSizeTopLeft">16dp</item>
<item name="cornerSizeBottomRight">16dp</item>
<item name="cornerSizeBottomLeft">16dp</item>
</style>
Run Code Online (Sandbox Code Playgroud)
使用代码,您可以使用以下内容将自定义ShapeAppearanceModel
应用于卡片的角落:
float radius = getResources().getDimension(R.dimen.my_corner_radius);
cardView.setShapeAppearanceModel(
cardView.getShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.setTopRightCornerSize(0)
.build());
Run Code Online (Sandbox Code Playgroud)
我有一个解决方案,但它需要 v21 Lollipop 及以上版本。您可以通过编程方式执行此操作,如下所示:
在你的活动课中有public static int radius = 20;
和 在你的Oncreate()
;
CardView card = findViewById(R.id.my_card);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
makeCustomOutline(card);
}
Run Code Online (Sandbox Code Playgroud)
然后定义函数如下:
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void makeCustomOutline(CardView card){
card.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(0, 0, view.getWidth(),
(view.getHeight() + radius), (float)radius );
}
});
card.setClipToOutline(true);
}
Run Code Online (Sandbox Code Playgroud)
通过使用该setRoundRect()
方法,您可以控制卡片视图的哪个角获得半径,哪个角不获得半径。上面的代码只会使顶角变圆,底角不会变圆。
参考:
归档时间: |
|
查看次数: |
2475 次 |
最近记录: |