如何从资源中获取视图?

9

我有一个UI,我动态构建它。我希望将某些组件放在XML资源文件中。所以我这样做:

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+android:id/titreItem"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
</TextView>

我看到有关于在文件res/layout/titreitem.xml中的内容,但我不知道如何将其放入我的用户界面中。因此,在activity.onCreate中,我想要做一些类似以下的事情:

RelativeLayout myBigOne = new RelativeLayout(this);
TextView thingFromXML = [what here ? ];
myBigOne.addView(thingFromXML);
setContentView(myBigOne);
2个回答

35
使用 LayoutInflater 可以填充整个布局,而不必动态创建它。
LayoutInflater li = LayoutInflater.from(context);
View theview = li.inflate(R.layout.whatever, null);

7

这种方法似乎有点不正确。你应该像你的TextView一样在xml中放置RelativeLayout,并填充整个xml。之后,你就可以自由地向你的布局中添加视图了。所以,请按照以下方式操作:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+androi:id/relLayout>
  <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+android:id/titreItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  </TextView>
</RelativeLayout>

在您的活动中:

setContentView(R.layout.titreitem);
RelativeLayout layout = (RelativeLayout)findViewByid(R.id.relLayout);
layout.addView(...);

感谢st0le的回答;他的答案很有趣,但我只有一个“被采纳的答案” :-) - Istao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接