以编程方式组合几种类型的XML布局



我有一个要求,其中有2个程序化生成的屏幕和2个xml布局。现在我需要对这些布局进行多次合并。

例如,我有屏幕1 -编程创建,屏幕2 -编程创建,屏幕3-从xml布局,屏幕4 -从xml布局

我的最终布局设计应该是一个单一的屏幕,屏幕1,屏幕2,屏幕3,屏幕4,屏幕2…根据我输入的屏幕数量,所有屏幕共享相同的屏幕空间。请告诉我方法。一些屏幕有相对布局和一些线性布局。所以它应该把这些结合起来。

您需要在主布局上调用addView()。一旦建立了主布局(包含所有其他布局),addView()方法将向现有的主布局添加新视图。

要添加新布局,首先需要对其进行充气。

LinearLayout primaryLayout;
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
LinearLayout newLayout = (LinearLayout)layoutInflater.inflate(R.layout.your_new_layout, null, false);
primaryLayout.addView(newLayout);

AddView还提供了一个索引选项,用于将新布局放置在主布局的特定位置。

尝试从一个空白的XML布局开始(例如称为primary_layout):

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

</RelativeLayout>

然后,当你的活动开始时,首先设置它,然后根据需要膨胀和添加:

setContentView(R.layout.primary_layout);
LinearLayout primaryLayout = (LinearLayout) findViewById(R.id.primaryLayout);

然后你可以将你的新视图添加到那个视图中。至于多次添加,我认为这是通过引用完成的,所以它只看到一个视图。尝试在方法中构建视图,然后返回视图。如:

private View buildNewView(){
    LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );  
    LinearLayout newView = (LinearLayout)layoutInflater.inflate( R.layout.my_new_view null, false );

    return newView ;
}

通过primaryLayout.addView(buildNewView();调用

您可以查看Fragments。它们似乎正是你所需要的。以下是培训和API指南的链接。

在您的xml文件中,您可以在LinearLayout父元素中指定4个子布局,每个子布局都有一个属性android:layout_weight="1",因此每个子布局只占用相同数量的空间。如果在纵向方向,建议设置android:layout_width="match_parentandroid:layout_height="0dp"现在,您可以将每个子布局的id标记为id1, id2, id3等,但您也可以将两个布局标记为android:id="@+id/fragment_container_firstandroid:id="@+id/fragment_container_second

在Java代码中,您将设置contentView作为xml文件的id (setContentView(R.layout.myXMLLayout);),通过以下培训指南链接创建Fragment的两个实例我上面提供,并使用getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container_first, firstFragment).commit();getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container_second, secondFragment).commit();之类的东西将这些视图添加到您之前在xml文件中设置的容器中(如果您正在使用支持库,这就是培训指南使用的)。
我真的希望这能帮到你。你可以用Fragments构建一个非常灵活的UI。例如,稍后,您可以在运行时用其他片段替换前两个片段,从而增加灵活性。你甚至可以针对不同的屏幕尺寸设置不同的ui,在手机上设置更紧凑的视图,但在平板电脑等更大的屏幕上提供更多功能。

如果这对你有帮助,我很想听到反馈!

最新更新