[英]How to make textview as card view in android using background resource
[英]How to show card view background like progress in Android?
我想設置app:cardBackgroundColor
的CardView
是這樣的:
<-----x----->
|-----------|------|
| color1 |color2|
|-----------|------|
其中x
是CardView
具有color1
百分比,默認情況下,整個背景色應為color2
,如何在代碼中動態設置? (最好是Kotlin
)
我認為最簡單的方法是根據文檔將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)
好的,您將需要做更多的研究,試驗和錯誤; 但是,為了讓您起步,我能想到的唯一方法是:
在運行時創建自定義漸變,然后從定義的“ x”中選擇值。 (*)
創建一個class CustomCardView: CardView()
重寫onDraw
或您認為適合繪制背景的任何其他方法,也將需要“ x”值(*)
結合使用這兩種解決方案,並讓您的CustomCardView
在運行時構造漸變,並使用上面1和2中的代碼將其設置為背景。
(*)如果“ x”是您希望人們在設計時通過XML更改的動態值,則需要創建一個自定義屬性,並讓CustomCardView
選擇/讀取該值(如果存在)。
在評論方面,我的意思是您可以這樣:
<?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的寬度和高度。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.