3

我有一个如下所示的 xml 文件,我将使用它来设置背景Textview

行.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>

上面的 Xml 我将在 main.xml 中设置为 TextView 的背景,如下所示:

主要的.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"
/>

但我希望通过代码而不是 Xml 来完成这项工作。我已经完成了我在 Xml 中所做的所有事情,例如通过代码动态地使用字体、宽度、高度、字体,但无法设置我在 Xml 文件中提到的背景。我们如何将 XML 文件的内容设置为 textview 的背景,类似于我们在 main.xml 中将背景设置为 XML。

在我这样做的代码中:

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

但是我没有找到如何设置背景,即如何将 XML 内容设置为背景?
谁能帮我解决这个问题?
提前致谢,

4

2 回答 2

7

我认为您正在寻找的方法是setBackgroundDrawable(Drawable d).

这将使用给定的 Drawable 设置背景。所以它看起来像这样:

TextView t1 = (TextView) findViewById(R.id.rowtext3);
t1.setBackgroundDrawable(row);
于 2010-10-10T19:49:46.663 回答
0

如果我对您的理解正确,findViewById(int id)那么您正在寻找 Activity 类。检索视图后,可以使用 设置背景setBackgroundResource(int id)。参数id可以在您生成的 R 文件中找到,例如findViewById(R.drawable.row).

于 2010-10-10T19:31:53.313 回答