2010-12-05 118 views
4

我有一个用户界面,我动态构建它。我应该把一些组件放在一个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); 

回答

7

做法似乎没有什么不正确。您应该将RelativeLayout放置到您的TextView所创建的xml中,然后膨胀整个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(...); 
+0

还要感谢st0le;他的回答很有意思,但我只有一个“接受的答案”:-) – Istao 2010-12-05 16:03:01

23

使用LayoutInflater ....整个布局可以膨胀,而不动态创建它....

LayoutInflater li = LayoutInflater.from(context); 
theview = li.inflate(R.layout.whatever, null) 
+0

无法解析法 '膨胀(INT)' – 2017-08-18 10:36:07