【发布时间】:2013-11-18 18:48:18
【问题描述】:
我想创建一个接收百分比并仅动态显示这部分背景的视图,作为参数。
例如使用参数 0.8 创建视图时;背景仅在视图宽度的 80% 处绘制(左侧填充 0%,右侧填充 20%)。
我尝试创建一个 DrawableGradient 作为 View 背景,但它与整个背景重叠,我无法调整此背景的大小。
我的下一个选择是创建 InsetDrawable 或 Layer-List 就像这个答案:Android drawable with background and gradient on the left,但我无法动态更改填充。
我目前使用的例子: res/layout/acitvity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="5dp"
tools:context=".MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/percentage_background_80"
android:text="80%"
android:textSize="16sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/percentage_background_20"
android:text="20%"
android:textSize="16sp"/>
</LinearLayout>
可绘制/percentage_background_20.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="5dp"
android:drawable="@drawable/background"
android:left="5dp"
android:right="5dp"
android:top="5dp"/>
<item
android:bottom="5dp"
android:drawable="@drawable/view_background"
android:left="5dp"
android:right="200dp"
android:top="5dp"/>
</layer-list>
可绘制/percentage_background_80.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:bottom="5dp"
android:drawable="@drawable/background"
android:left="5dp"
android:right="5dp"
android:top="5dp"/>
<item
android:bottom="5dp"
android:drawable="@drawable/view_background"
android:left="5dp"
android:right="50dp"
android:top="5dp"/>
</layer-list>
drawable/background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="@android:color/white" />
</shape>
drawable/view_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><shape>
<gradient
android:angle="0"
android:startColor="@android:color/holo_blue_dark"
android:endColor="@android:color/white"
android:type="linear" />
</shape>
</item>
</selector>
这是它的外观,但我无法从源代码更改列表中的填充值。你知道我该如何实现吗?
澄清: 在 drawable/percentage_background_80.xml 和 drawable/percentage_background_20.xml 中有元素:
android:right="XXXdp"
我想以编程方式更改 XXXdp 的值。
【问题讨论】:
-
你为什么不使用 ClipDrawable ?
-
嗯,ClipDrawable 几乎是我所需要的,但它会从两侧夹住 Drawable。我不能只从右侧剪辑它。
-
在 ClipDrawable 构造函数中使用适当的重力
-
哦,是的,你是对的。但是还有一个问题,因为 ClipDrawable 去掉了背景 drawable 的一部分,所以 GradientDrawable 在这里没有用。你知道其他可以调整其子级而不是剪切它的 Drawable 吗?
-
ScaleDrawable?我建议阅读一些关于 Drawable 类的文档
标签: android android-layout user-interface