首页 > 解决方案 > 如何将 xml 布局设置为线性布局的视图

问题描述

我正在开发一个项目,我想在一个页面中创建两个部分,例如,我将使用给定的部分(下面的 xml 代码)创建一个主页。它将在main_activity.xml文件上完成,我想将底部的视图设置为LinearLayout不同的布局资源文件。其中将包含一些不同的代码。我怎样才能做到这一点?

 <RelativeLayout>
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:weightSum="2"

<LinearLayout>
                android:id="@+id/Top"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
</LinearLayout>
<LinearLayout>
                android:id="@+id/Bottom"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
</LinearLayout>
</RelativeLayout/>

标签: androidxmlandroid-layoutandroid-linearlayout

解决方案


正如我从帖子中了解您的问题,我建议您为底部视图创建单独的布局并将其包含在您的主 xml 布局文件中

在这里,如果我想分别添加 2 个顶视图和底视图,您可以在布局中添加 2 个文件

假设我有两个布局文件 top_view.xml 和 bottom_view.xml

top_view.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="top button"/>
</LinearLayout>

bottom_view.xml

 <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bottom button"/>
</LinearLayout>

并且在 main_activiy.xml 文件中包含这两个文件

main_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/d_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/top_view" />

<include
    layout="@layout/bottom_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />
</RelativeLayout>

您可以访问 main.java 文件中包含的布局的所有控件


推荐阅读