2012-05-13 17 views
2

我有一个简单的Android项目,其中包含一个用xml定义的矩形,但是我找不到一种用语法在程序中用纯色填充它的方法。如何以编程方式填充在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被定义/抽拉/ 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); 

感谢

回答

1

晚的答案,但也许可以帮助...我有一个类似的问题,可绘制形状。我试图访问我的可绘制形状,发现可绘制的形状是GradientDrawable。所以如果你想获得访问权限,试试这个:

GradientDrawable yourShape = (GradientDrawable)getResources().getDrawable(
      R.drawable.yourShape); 
相关问题