【问题标题】:Create views programmatically using XML on Android在 Android 上使用 XML 以编程方式创建视图
【发布时间】:2012-12-15 04:12:22
【问题描述】:

我想在 XML 中创建一个 UI 布局,并将其作为子项插入到现有视图中(它将被插入多次)。

例如,以下是 XML 文件将包含的内容:

<RelativeLayout
    android:id="@+id/relativeLayout1" >
    <Button android:id="@+id/myButton"
        android:text="@string/mystring" />
</RelativeLayout>

现在我得到了父 LinearLayout,现在想将该 XML 文件添加为子视图,例如:

LinearLayout linear = (LinearLayout) findViewById(R.id.myLayout);

// need to create a view object from the xml file
linear.addView(myXmlObject);

是否可以将 XML 资源转换为视图类型?如果是这样,我该怎么做?

【问题讨论】:

  • @Eric 哇哦,我错过了。但是等等!
  • @Sam 我怎么……我只是……好吧,你完全拥有我。
  • 我觉得你应该寻找某种适配器。

标签: android xml


【解决方案1】:

我相信你想要LayoutInflater。假设您的示例 XML 在文件 custom_layout.xml 中:

LayoutInflater inflater = LayoutInflater.from(context);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_layout, null, false);

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout);
linear.addView(layout);

【讨论】:

  • 谢谢老兄。你节省了我的时间
  • 你是如何处理按钮点击的?我的意思是每一行的按钮点击都有不同的功能。
  • 谢谢。它帮助了我
猜你喜欢
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
相关资源
最近更新 更多