How to dynamically set TextView background from Xml file

I have an xml file as shown below, which I will use to set the 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>

I will set the above Xml as the background for the TextView in main.xml, as shown 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 be done from code, not from Xml. I did everything that I did in Xml, like font, width, height, font dynamically using code, but could not install Background, which I mentioned in the Xml file. How we can set the contents of the Xml file as the background for the text view, similar to how we set the background as XML in main.xml.

In the code I did like this:

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

, , XML- ?
- ?
, ,

+3
2

, , , setBackgroundDrawable(Drawable d).

, Drawable. :

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

, findViewById(int id) Activity - , . , setBackgroundResource(int id). R , . findViewById(R.drawable.row).

0

Source: https://habr.com/ru/post/1768878/


All Articles