2

我有一个简单的 Android 项目,它在 xml 中定义了一个矩形,但我找不到一种方法以编程方式用纯色填充它。

main.xml 文件有以下内容

<ImageView
    android:id="@+id/Smoke20"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/editText2"
    android:layout_marginLeft="26dp"
    android:src="@drawable/zonebox" />

其中 zonebox 在 res/drawable/zonebox.xml 中定义如下

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 

android:shape="rectangle" >

<size
    android:width="80sp"
    android:height="20sp" />

<stroke
android:width="1dp"
android:color="#88888888" />

<!--  solid
    android:color="#0A0" />    
-->
</shape>

在我的代码中,我可以例如更改矩形边界的颜色,例如

int colourBox = getResources().getColor(R.color.fire2_fire_color);
View rectTest = findViewById(R.id.Smoke20);
rectTest.setBackgroundColor(colourBox);

但我无法在代码中复制在 xml 中如此容易完成的“solid”属性,如图所示已注释掉。我显然是以错误的方式解决这个问题,但经过大量研究,我仍然一无所知。

我已经查看了如下获取 xml 资源的方法,但这也没有提供合适的方法来填充矩形。

ShapeDrawable viewTest = (ShapeDrawable)getResources().getDrawable(R.id.Smoke20);

谢谢

4

1 回答 1

1

迟到的答案,但也许有帮助......我在可绘制形状方面遇到了类似的问题。我试图访问我的 shape-drawable 并发现 shape drawable 是 GradientDrawable。因此,如果您想获得访问权限,请尝试以下操作:

    GradientDrawable yourShape = (GradientDrawable)getResources().getDrawable(
            R.drawable.yourShape);
于 2012-10-19T19:46:57.127 回答