Set border and background color of textView
Asked Answered
S

2

16

I have a TextView defined in XML and i would like to set background color AND border to it. Problem i have is that in XML i already use android:background for setting border resource, so i can't use it once again for background color. Can someone please guide me to right direction?

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" />
Sisk answered 13/3, 2013 at 13:57 Comment(0)
Y
31

You should create a XML drawable for this, which can then be set as your single background. Here is what you are wanting (a rectangle with a different color border - replace gradient with if you don't want that).

This will go in your 'drawable' folder:

<?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>
Yeargain answered 13/3, 2013 at 14:2 Comment(0)
H
3

Via 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);

Via 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" />

This is the API page about this topic: http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromXml

Habituate answered 18/9, 2013 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.