我有同样的问题,但我也实现了另一种方法。
这是 XML:
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:id="@+id/view_card_header_large_border_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
<com.google.android.material.card.MaterialCardView
android:id="@+id/view_card_header_large_border_base"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
app:cardBackgroundColor="?paper_color"
app:cardCornerRadius="10dp"
app:cardElevation="0dp"/>
</FrameLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/view_card_header_large_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
....
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
这是代码:
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
new int[] {leftColor, rightColor});
// card background
gradientDrawable.setAlpha(70);
gradientDrawable.setCornerRadius(borderBaseView.getRadius());
container.setBackground(gradientDrawable);
// card border's background, which depends on the margin that is applied to the borderBaseView
gradientDrawable.setAlpha(90);
gradientDrawable.setCornerRadius(12dp);
borderContainer.setBackground(gradientDrawable);
这个想法是将背景设置为两个视图,顶视图覆盖“边框”基本视图,但留下一个1dp
边距作为“边框”。
这样您将在视图中具有渐变背景,并且在边框中也将具有渐变背景。