2010-10-10 122 views
3

我有一個xml文件像下面我將使用設置背景Textview
如何設置一個TextView背景動態地從xml文檔

row.xml

 <?xml version="1.0" encoding="utf-8"?> 
     <shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient android:endColor="#CCCCCC" android:startColor="#CCCCCC" 
     android:angle="270" /> 
     <stroke android:width="1dp" android:color="#999999" /> 
     <corners android:bottomRightRadius="0dp" 
     android:bottomLeftRadius="0dp" android:topLeftRadius="0dp" 
     android:topRightRadius="0dp" /></shape> 

上面的XML我將在main.xml中如下設置爲背景的TextView:

main.xml中

<TextView 
android:id="@+id/rowtext3" 
android:text="Availablity" 
android:layout_height="25px" 
android:layout_width="60px" 
android:textSize="10px" 
android:textStyle="bold" 
android:textColor="@color/black" 
android:gravity="center" 
android:background="@drawable/row" 
/> 

但我希望這樣做是從代碼而不是Xml.I已經完成了我在Xml中完成的所有操作,例如字體,寬度,高度,動態代碼的字體,但無法設置我在Xml文件中提到的背景。我們如何將XML文件的內容設置爲textview的背景,類似於我們在main.xml中將背景設置爲XML。

在代碼中我曾經做過這樣的:

t1=new TextView(this); <br> 
    t1.setText(ed1.getText()); <br> 
    t1.setHeight(25); <br> 
    t1.setWidth(60); <br> 
    t1.setTextSize(10); <br> 

但我沒有找到如何設置背景即如何設置XML內容作爲背景?
任何人都可以幫助我解決這個問題?
在此先感謝,

回答

7

我認爲你要找的方法是setBackgroundDrawable(Drawable d)

這將使用給定的Drawable設置背景。所以它看起來像這樣:

TextView t1 = (TextView) findViewById(R.id.rowtext3); 
t1.setBackgroundDrawable(row); 
+0

我試過你建議如下的方式:TextView tt =(TextView)findViewById(R.id.ttt); tt.setBackgroundDrawable(R.drawable.row);我得到的錯誤爲「類型View中的方法setBackgroundDrawable(Drawable)不適用於參數(int)」。我該如何解決這個問題?但我也在活動文件中動態創建textview,不需要我從XML文件中獲取參考。 – 2010-10-11 05:11:01

+5

這是因爲'setBackgroundDrawable()'不接受一個int作爲參數。嘗試使用相同的技術,但使用接受int資源(可繪製對象)ID的setBackgroundResource()方法。 – 2010-10-11 13:04:00

+0

超級,它運作良好。非常感謝 – 2010-10-11 18:55:21

0

如果我理解你正確,findViewById(int id)從Activity類是你要找的。當您檢索到視圖時,可以使用setBackgroundResource(int id)設置背景。參數id可以在您生成的R文件中找到,例如, findViewById(R.drawable.row)

+0

t1.setBackgroundResource(findViewById(R.drawable.row)); – 2010-10-11 04:57:26

+0

嗨,我給你喜歡你在我的活動建議:t1.setBackgroundResource(findViewById(R.drawable.row));它顯示錯誤爲「類型視圖中的方法setBackgroundResource(int)不適用於參數視圖。」如何解決此錯誤以便爲TextView設置背景。 – 2010-10-11 04:59:53