2012-12-15 101 views
16

我想用XML创建UI布局,并将其作为子视图插入现有视图(它将被插入多次)。在Android上使用XML以编程方式创建视图

例如,这里是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资源转换为视图类型?如果是这样,我将如何做到这一点?

+1

@Eric哦,哇,我错过了。可是等等! – Sam

+1

@Sam我怎么......我只是......好吧,你完全拥有我在那里。 – Eric

+0

感觉像我这样的人,你应该找某种适配器。 – FoamyGuy

回答

61

我相信你想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); 
+0

谢谢老兄。你节省了我的时间 –

+0

你是如何处理按钮点击的?我的意思是每行的按钮点击具有不同的功能。 – user4057066

相关问题