【问题标题】:Create TextView from template XML file从模板 XML 文件创建 TextView
【发布时间】:2012-04-25 04:12:48
【问题描述】:

我在文件simple_txt.xml 中有一个简单的TextView 模板

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:textSize="18sp" >
</TextView>

在一些代码中,我需要从这个模板创建一个TextView,类似于:

TextView txt = new TextView(this);
txt.setLayout(R.layout.simple_txt);//???

然后用它做点什么(setText 等)。如何创建这样的TextView

【问题讨论】:

  • 但是为什么??为什么不直接用 findViewById() 获取 TextView ????
  • 因为我在主布局中没有这个文本视图,我需要从模板文件创建它然后添加到主布局

标签: android layout textview


【解决方案1】:
TextView txt = (TextView) View.inflate(this, R.layout.simple_txt, null);

【讨论】:

  • fyi,通常不建议为最后一个(根)参数传递 null,但在这里这样做是必不可少的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多