2012-05-13 23 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); 
相關問題