Android_programmer_camera
Android_programmer_camera

Reputation: 13349

How to set Background of a TextView dynamically from Xml file

I have an xml file like below which I will use to set background for Textview:

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>

The above Xml I will set as background for TextView in main.xml as below:

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

But I want this to do from code rather than Xml.I have done everything that I have done in Xml like font, width, Height, font dynamically through code, but not able to set Background that I mentioned in Xml file. How can we set content of Xml file as background to textview similar to how we set background as XML in main.xml.

In the code I have done like this:

    t1=new TextView(this); <br>
    t1.setText(ed1.getText()); <br>
    t1.setHeight(25); <br>
    t1.setWidth(60); <br>
    t1.setTextSize(10); <br>

But I didn't find how to set background i.e. how to set XML content as background?
Can any one help me in sorting out this issue?
Thanks In Advance,

Upvotes: 3

Views: 22880

Answers (2)

user340145
user340145

Reputation:

If I understand you correctly, findViewById(int id) from the Activity class is what you're looking for. When you have retrieved the view, you can set the background using setBackgroundResource(int id). The parameter id can be found in your generated R-file, e.g. findViewById(R.drawable.row).

Upvotes: 0

Tyler Treat
Tyler Treat

Reputation: 14988

I think the method you're looking for is setBackgroundDrawable(Drawable d).

This will set the background using the given Drawable. So it would look something like this:

TextView t1 = (TextView) findViewById(R.id.rowtext3);
t1.setBackgroundDrawable(row);

Upvotes: 7

Related Questions