设置textView的边框和背景颜色

16

我在XML中定义了一个TextView,我想为它设置背景颜色和边框。问题是我已经使用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" />
2个回答

31

你应该创建一个XML drawable,并将其设置为单一背景。这是你想要的(一个带有不同颜色边框的矩形 - 如果你不想要渐变,请将渐变替换为边框颜色)。

这将放在你的“drawable”文件夹中:

<?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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接