2013-02-17 54 views
1

我有一个布局,我想用2个文本视图和一个按钮组成项目。我不知道将有多少项目将填充我的布局。 因为我不知道在什么时候编写layout.xml我想添加多少项目,那意味着我必须在java中添加项目而不是xml。但我不喜欢在java中构建GUI,因为它看起来很丑。建设灵活的GUI

有谁知道我是否可以为我的物品创建一个xml文件,然后在执行过程中将新物品添加到我的布局中?

我已经写了一些伪代码,试图证明我想要完成的任务:

MainLayout.xml

//My empty Layout 
<Layout myMainLayout > 
</RelativeLayout> 

Fragment_post.xml

//one post 
<TextView/> 
<TextView/> 
<Button/> 

在代码某处

setContentView(R.layout.MainLayout); 
MyMainLayout.addFragment(R.layout.Fragment_post); 

回答

0

您可以添加fragment_post.xml无论你想:

LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
LinearLayout view=(LinearLayout)inflater.inflate(R.layout.yourfragment, null); 
yourLayout.addView(view); 

请不要混淆片段用一块GUI的。详情请看这里:http://developer.android.com/guide/components/fragments.html

0

当然你可以这样做。只需为您的活动设置一个初始空白布局即可。

onCreate() 
{ 
setContentView(R.layout.initial_layout); 
} 

然后获得并保持到主要布局的参考。

LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
RelativeLayout mainLayout=(RelativeLayout)inflater.inflate(R.layout.initial_layout, null); 

接下来,在需要时向布局添加新视图。

LinearLayout view=(LinearLayout)inflater.inflate(R.layout.fragment_post, null); 
mainLayout.addView(view); 

但请注意,这里所指的片段不是android所指的片段。在此处了解实际Android碎片:

http://developer.android.com/guide/components/fragments.html