【问题标题】:How to set Background of a TextView dynamically from Xml file如何从 Xml 文件动态设置 TextView 的背景
【发布时间】:2010-10-10 19:20:18
【问题描述】:

我有一个如下所示的 xml 文件,我将使用它来为 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>

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

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

但我希望通过代码而不是 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 内容设置为背景?
谁能帮我解决这个问题?
提前致谢,

【问题讨论】:

    标签: android textview xml-drawable


    【解决方案1】:

    我想你要找的方法是setBackgroundDrawable(Drawable d)

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

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

    【讨论】:

    • 我尝试了你建议的方式如下:TextView tt=(TextView)findViewById(R.id.ttt); tt.setBackgroundDrawable(R.drawable.row);我收到错误,因为“View 类型中的方法 setBackgroundDrawable(Drawable) 不适用于参数 (int)”。我该如何解决这个问题?但我也在活动文件中动态创建文本视图,我不需要从 XML 文件中获取参考。
    • 这是因为 setBackgroundDrawable() 不接受 int 作为参数。尝试使用相同的技术,但使用接受 int 资源(可绘制对象)ID 的方法 setBackgroundResource()
    • 嗨,你能给我一个示例代码,了解如何通过代码动态创建一个 RelativeLayout,其中 2 个文本视图位于另一个之下。我想通过代码实现 android:layout_below 功能。
    【解决方案2】:

    如果我理解正确,来自 Activity 类的findViewById(int id) 就是您要查找的内容。检索视图后,您可以使用setBackgroundResource(int id) 设置背景。参数 id 可以在您生成的 R 文件中找到,例如findViewById(R.drawable.row)

    【讨论】:

    • t1.setBackgroundResource(findViewById(R.drawable.row));
    • 嗨,我给了你在我的活动中建议的那样:t1.setBackgroundResource(findViewById(R.drawable.row));它显示错误为“类型视图中的方法 setBackgroundResource(int) 不适用于参数视图。”如何解决此错误以便为 TextView 设置背景。
    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多