构建灵活的GUI

时间:2013-02-17 09:58:09

标签: android xml user-interface runtime

我有一个布局,我希望用2个文本视图和一个按钮组成的项目填充。我事先不知道将填充布局的项目数量。 因为我不知道在编写layout.xml时想要添加多少项,这就意味着我必须在java中添加项而不是xml。但我不喜欢在java中构建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);

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

相关问题