android - 动态改变背景颜色

标签 android xml layout

我正在使用 RangeSeekBar 为 3 个条件设置一些值(即 Green=OK、Amber=Warning、Red=evacuate)...我正在使用 xml drawable 来设置这样的背景

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient 
        android:startColor="#27F70C" 
        android:centerColor="#FFBF00"
        android:endColor="#FC0505" 
        android:angle="0" />

    <corners android:radius="0px" />

    <stroke 
        android:width="2dp" 
        android:color="#70555555" />

    <stroke 
            android:width="0dp" 
            android:color="#70555555" />
</shape>

结果是这样的 enter image description here

现在我想根据搜索栏值更改背景颜色,这样如果我更改范围,它应该会像这样更改背景颜色 enter image description here

我知道我可以通过编程方式更改渐变,但如何缩小开始颜色并增加结束颜色? 有人对此有解决方案吗?

谢谢

最佳答案

尝试在 RangeSeekBar 下创建三个 View,并在 slider 移动时更新每个 View 的宽度。

非常粗略地,这可能看起来像:

<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
     <View
         android:id="@+id/green"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#00FF00"/>
     <View
         android:id="@+id/orange"
         android:layout_toRightOf="@id/green"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#FFFF00"/>
     <View
         android:id="@+id/red"
         android:layout_toRightOf="@id/orange"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#FF0000"/>
     <RangeSeekBar android:layout_width="300dp" android:layout_height="wrap_content">
</RelativeLayout>

在此示例中,您将更新三个颜色 View 的宽度,以便它们随着 slider 的移动而加起来达到 300dp。

您可以为三个 View 的背景使用纯色,这看起来就像您的第二张图片,或者创建三个渐变(绿色到绿-黄、黄-橙、橙-红)。

关于android - 动态改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24142284/

相关文章:

android - 忽略 DefaultHttpClient 中的 ssl 错误

java - org.xml.sax.SAXParseException : Premature end of file for *VALID* XML

java - Swing/AWT - 以编程方式创建 GUI

java - 我应该如何插入布局以及什么布局?

java - FloatingActionButton 在 KitKat 上不显示

android - 从当前目的地无法找到导航操作/目的地

android - 将我的 apk 推送到/system/app

asp.net - 导入 SiteFinity

c# - 如何从 XmlElement 或 XPathNavigator 获取行号

html - 在 flexbox 中遇到障碍,将一个 div 放在另一个下面,同时将第三个放在一边