我有一個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內容作爲背景?
任何人都可以幫助我解決這個問題?
在此先感謝,
我試過你建議如下的方式:TextView tt =(TextView)findViewById(R.id.ttt); tt.setBackgroundDrawable(R.drawable.row);我得到的錯誤爲「類型View中的方法setBackgroundDrawable(Drawable)不適用於參數(int)」。我該如何解決這個問題?但我也在活動文件中動態創建textview,不需要我從XML文件中獲取參考。 – 2010-10-11 05:11:01
這是因爲'setBackgroundDrawable()'不接受一個int作爲參數。嘗試使用相同的技術,但使用接受int資源(可繪製對象)ID的setBackgroundResource()方法。 – 2010-10-11 13:04:00
超級,它運作良好。非常感謝 – 2010-10-11 18:55:21