我要这样设置app:cardBackgroundColor
中的CardView
:
<-----x----->
|-----------|------|
| color1 |color2|
|-----------|------|
其中x
是CardView
中有color1
的百分比,
默认情况下,整个背景色应为color2
,
如何在代码中动态设置? (最好是Kotlin
)
答案 0 :(得分:0)
好的,您将不得不做更多的研究,试验和错误;但要开始使用,我想到的唯一方法是:
在运行时创建自定义渐变,从定义的“ x”中选择值。 (*)
创建一个覆盖class CustomCardView: CardView()
的{{1}}或您认为合适的其他方法来绘制背景,也将需要“ x”值(*)
组合两个解决方案,并让您的onDraw
在运行时构造渐变,并使用上面1和2中的代码将其设置为背景。
(*)
如果您希望人们在设计时通过XML更改“ x”的动态值,则需要创建一个自定义属性,并让CustomCardView
选择/读取该值(如果存在)。
答案 1 :(得分:0)
在评论方面,我的意思是您可以这样;
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="150dp"
app:cardCornerRadius="16dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<LinearLayout
android:id="@+id/left_side"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_toStartOf="@+id/right_side"
android:layout_toLeftOf="@+id/right_side"
android:background="@color/colorPrimary"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/right_side"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="@color/colorPrimaryDark"
android:orientation="vertical" />
</RelativeLayout>
</android.support.v7.widget.CardView>
您可以更改布局或cardview的宽度和高度。 希望这会有所帮助。
答案 2 :(得分:0)
我认为最简单的方法是根据docs将CardView
的内容放入FrameLayout
内:
子视图是在堆栈中绘制的,最近添加的子视图位于顶部。 FrameLayout的大小是其最大子项(加上填充)的大小(可见或不可见)(如果FrameLayout的父项允许)。仅当setConsiderGoneChildrenWhenMeasuring()设置为true时,用于View.GONE的视图才用于调整大小。
假设这是CardView
布局:
<androidx.cardview.widget.CardView>
<!-- your contents -->
</androidx.cardview.widget.CardView>
将其更改为:
<androidx.cardview.widget.CardView>
<FrameLayout>
<LinearLayout android:orientation="horizontal">
<View
android:id="@+id/left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0"
android:background="color1"/>
<View
android:id="@+id/right"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="100"
android:background="color2"/>
</LinearLayout>
<!-- your contents -->
</FrameLayout>
</androidx.cardview.widget.CardView>
在代码中:
findViewById<View>(R.id.left).layoutParams = LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.MATCH_PARENT, x)
findViewById<View>(R.id.right).layoutParams = LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.MATCH_PARENT, 100f - x)