2013-03-13 57 views
14

我有一個XML定義的TextView,我想設置背景顏色和邊框。 我遇到的問題是,在XML中我已經使用android:background來設置邊框資源,所以我不能再次使用它作爲背景顏色。 有人可以引導我正確的方向嗎?設置文本的邊框和背景顏色查看

Border.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > 
    <solid android:color="#ffffff" /> 
    <stroke android:width="1dip" android:color="#7F000000"/> 
</shape> 

的TextView

<TextView 
     android:id="@+id/editor_title" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:background="@drawable/title_border"   
     android:padding="5dp" 
     android:text="@string/editor_title"    
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

回答

29

您應該爲此創建XML繪製,然後可以設置爲你的單身背景。這是你想要的(一個帶有不同顏色邊框的矩形 - 如果你不想要的話,用其替換漸變)。

這將在您的 '繪製' 文件夾中去:

<?xml version="1.0" encoding="utf-8"?> 
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <stroke android:width="3dp" android:color="@color/blue_button_border" /> 
    <gradient 
     android:startColor="@color/gradient_end" 
     android:endColor="@color/gradient_start" 
     android:angle="-90" /> 
</shape> 
3

通過Java:

TextView c1 = new TextView(activity); 
c1.setTextColor(getResources().getColor(R.color.solid_red)); 
c1.setText("My Text");  

TextView test = (TextView) view.findViewById(R.id.textView2); 
test.setBackgroundResource(R.color.holo_green_light); 

通過XML:

<TextView 
     android:text="2" 
     android:textSize="200sp" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/textView2" 
     android:style="@style/textviewStyle" 
     android:background="@android:color/holo_green_light" 
     android:gravity="center" 
     android:textColor="#EEEEEE" 
     android:layout_alignParentRight="true" /> 

這是關於這一主題的API頁面: http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromXml