【问题标题】:Change colour of a shape in Java for Android after user input用户输入后在 Java for Android 中更改形状的颜色
【发布时间】:2015-04-23 23:20:54
【问题描述】:

我有一个简单的形状,它存储在 rect.xml 中,并作为“视图”的“背景”属性包含在另一个 xml 中。这两个代码是:

\res\layout\rect.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape"
android:shape="rectangle" >
<stroke android:width="2dp" android:color="#aaaaff" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"    >
</padding>
<solid android:color="#E6121A" />
<gradient
android:startColor="#000000"
android:endColor="#aaaaff"
android:angle="90"  >
</gradient>

<corners
android:radius="10dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" >
</corners>

</shape> 

我的另一个视图,显示为活动的内容包括:

<View
    android:id="@+id/myRectangleView"
    android:layout_width="25dp"
    android:layout_height="125dp"
    android:layout_below="@+id/tableLayout1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="35dp"
    android:background="@layout/rect" />

我想将 android:endColor 属性设置为另一种颜色,startColor 总是相同的。 提前感谢您的回答!

【问题讨论】:

    标签: java android xml colors shape


    【解决方案1】:

    我没有测试过这个,但是基于here的信息 你应该可以用这个设置颜色:

    GradientDrawable gradient = (GradientDrawable)yourView.getBackground();
    
    int startColor = Color.BLACK;
    int endColor = Color.RGB(0, 2, 255);
    gradient.setColors(new int[]{ startColor, endColor });
    

    请注意 GradientDrawable.setColors() 是在 API 级别 16/Android 4.1 中添加的(感谢unrulygnu!),为了支持更早的版本,您需要在每次想要更改时创建并设置一个新的GradientDrawable颜色,像这样:

    GradientDrawable gradient = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{startColor, endColor});
    gradient.setShape(GradientDrawable.RECTANGLE);
    yourView.setBackgroundDrawable(gradient);
    

    【讨论】:

    • 感谢您的实际帮助!
    • 这确实有效(经过测试);但是,GradientDrawable.setColors() 方法已添加到 JellyBean (API 16) 中的平台中。如果需要对 ICS(或以前的)的支持,那么需要跳过更多的环节……可能是将颜色存储为资源,然后在运行时构建背景。
    • 谢谢@unrulygnu,我不知道。包含在原始答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2019-01-29
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多