android - 以编程方式更改在另一个 xml 中用作背景的 border.xml 的 startColor?

标签 android xml shapes

我在 drawable 文件夹中有一个名为 border.xml 的 xml 文件。 在这个 xml 中我有

<!-- +++++++++++++++++++++  BORDER  +++++++++++++++++++ -->
<item> 
    <shape android:shape="rectangle">
        <solid
            android:id="@+id/shape_border_color" 
            android:color="@color/black" /> 
        <gradient 
            android:id="@+id/shapre_border_gradient" 
            android:startColor="@color/BurlyWood" 
            android:endColor="@color/Blue" 
            android:angle="270"
        /> 
<!-- ++++++++++++++++++++ ROUND CORNERS ++++++++++++++++++++++++++++ -->
        <corners
            android:id="@+id/shape_border_corners" 
            android:bottomRightRadius="7dp" 
            android:bottomLeftRadius="7dp" 
            android:topLeftRadius="7dp" 
            android:topRightRadius="7dp"
    /> 
    </shape>
</item>   

<!-- +++++++++++++++++++++++  BACKGROUND ++++++++++++++++++++++++++ -->
<item 
    android:left="5dp" 
    android:right="5dp"  
    android:top="5dp" >  
    <shape android:shape="rectangle"> 
        <gradient 
            android:id="@+id/shape_background" 
            android:id="@+id/hr_design_background_gradient" 
            android:startColor="@color/DarkOrchid" 
            android:endColor="@color/LawnGreen" 
            android:angle="270"/>
    </shape>
</item>    

我在我的 main.xml 文件中使用上面的 xml 文件作为 LinearLayout 的背景

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:padding="0dp"
    android:background="@drawable/border_o2">

在我的 Main.java Activity 中,我有兴趣更改边框的 开始和结束颜色 以及角的 backgroundRadius

例如,如果我使用的是 TextView,我知道如何更改某个 ID 的背景。但我不确定如何更改 Item/Shape/Gradiant 值。

谢谢

最佳答案

一种方法是定义第二个可绘制资源,称为 drawable/alternate_background.xml。在此文件中,您可以对替代颜色、半径值等进行编码。

然后您以编程方式加载备用资源。

linearLayout.setBackgroundResource(R.drawable.alternate_background);

FWIW,这种方法的一个优点是您的 View 仍然是外部化的。因此,您可以使用 Eclipse 布局编辑器来预览更改,而不是等到运行时才能看到更改的效果。

关于android - 以编程方式更改在另一个 xml 中用作背景的 border.xml 的 startColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102573/

相关文章:

安卓框架 : System service does not get permission(s)

java - XML 保留前导空格,但不保留尾随空格

android - 如何在 Android 中将 <vector> 放入 <shape> 中?

html - 带有 CSS 的圆形标签形状

Android-Studio:Gradle 找不到 HoloEverywhere

android - 使用 Mockito Kotlin 模拟对象而不是 Stubbing 方法

Android:非键盘输入法

python - “ascii”编解码器在执行 bs 时无法解码字节 0xcb

php - 为什么 SimpleXMLElement 返回一个空对象?

java - 根据用户输入打印菱形图案