2011-07-08 41 views
0

我有一個在我試圖運行的例子。 有2種方式來做到這一點..Android的TextView

// Get a drawable 
ColorDrawble redDrawable = (ColorDrawable).getResources().getDrawable(R.drawable.red_rectangle); 

//Set it as a background to a text view 
textView.setBackground(redDrawable); 

當我把這個在Eclipse IDE中我得到一個錯誤ColorDrawble不能被解析爲一個類型 我在主XML TextView的


<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <TextView android:layout_width="fill_parent" 
      android:id="@+id/texter" 
      android:layout_height="wrap_content" 
      android:text="this string"/> 


</LinearLayout> 

,並在字符串的XML文件中的資源

<resources> 
    <string name="hello">Hello World, ResourceTesterActivity!</string> 
    <string name="app_name">ResourceTester</string> 
    <drawable name="red_rectangle" >#f00</drawable> 
    <drawable name="blue_rectangle">#0000ff</drawable> 
    <drawable name="green_rectangle" >#f0f0</drawable> 
</resources> 

**

+0

爲什麼你將可繪製資源存儲在strings.xml中嗎? – Egor

+0

它來自一個adndroid的例子..從PRO android 2 http://www.amazon.com/Pro-Android-Sayed-Y-Hashimi/dp/1430226595 – RBad

回答

0

你可以簡單地使用這樣的繪製:

// Get a drawable 
Drawable redDrawable = YourActivity.this.getResources().getDrawable(R.drawable.red_rectangle); 

//Set it as a background to a text view 
textView.setBackgroundDrawable(redDrawable);//i've changed setBackground with setBackgroundDrawable. 

,或者你可以直接使用:

textView.setBackgroundResources(R.drawable.red_rectangle); 

注:清潔和重建項目,並運行它來測試 和對於drawable,你不需要在strings.xml中聲明它,只需在drawables文件夾中添加你的drawable,它就可以工作

+0

感謝您的回覆。認爲我需要使對象textView?我得到一個錯誤textView無法解析 – RBad

+0

請確保您的佈局包含一個textView,並重建您的項目:轉到菜單項目==>清潔==>選擇您的項目==>然後按確定。 – Houcine

+0

如果我將代碼更改爲此.. TextView tv =(TextView)findViewById(R.id.textView1); tv.setBackgroundResource(R.drawable.red_rectangle); 我在仿真器上出錯對不起! ResouceTester意外停止 – RBad

0

它應該是:

ColorDrawble redDrawable = (ColorDrawable) 
      getResources().getDrawable(R.drawable.red_rectangle); 

你不需要點(也許這是一個錯字)。

然後按Ctrl + Shift + O(組織導入)導入ColorDrawble類。

+0

感謝您的回覆。我gettign 2錯誤。 1. ColorDrawable無法解析爲一個類型,2. textView無法解析 – RBad

+0

是的,你是對的不需要一個點,仍然有問題的TextView。我必須聲明一個新的對象,如TextView textview = new Textview(textView); ?? – RBad

+0

如果我改變這個代碼.. TextView tv =(TextView)findViewById(R.id.textView1); tv.setBackgroundResource(R.drawable.red_rectangle); 我在仿真器上出錯對不起! ResouceTester意外停止 – RBad