如何从 XML 定义片段的布局?

2022-09-02 09:54:41

我正在尝试以与定义视图布局相同的方式在 XML 中定义片段的布局。

这可能吗?我尝试了几件事,但似乎都不起作用。

我的活动布局如下所示(主.xml):

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
  <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="full.lommeregner.Lommeregnerrv2Activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lommeregnerv2">
    </fragment>   

</ListView>

现在,由于我不是通过原始Java代码生成布局的忠实粉丝,因此我尝试按如下方式定义我的片段(fragment_lommeregner.xml):

  <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="full.lommeregner.Lommeregnerrv2Activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lommeregnerv2">
       <!-- my content was located here (some textviews, buttons and so on). -->
    </fragment> 

我做错了什么吗?如何通过 XML 定义片段的布局?


答案 1

片段的工作方式与活动非常相似,因为您需要一个Java类文件来配合它。你不能仅仅通过创建一个片段布局来创建一个片段 - 你需要一个片段的类:

  1. 为活动创建布局 XML 和活动子类
  2. 为片段创建布局 XML 和片段子类
  3. 在活动布局 XML 中将两者捆绑在一起(或者,如果要在 Java 代码中执行此操作,请使用 FragmentTransaction)

如果您尚未这样做,请阅读,重新阅读并消化此页面上的所有内容:https://developer.android.com/guide/components/fragments.html

那里有很多,但碎片现在是Android应用程序的重要组成部分,所以它是必读的。好消息是,片段的基础知识非常简单。


答案 2

只需作为属性添加到您的代码中:<fragment>

tools:layout="@layout/your_layout_xml"

在您的主容器中.xml(或标记容器)放入您的父容器(在本例中):<fragment>ListView

xmlns:tools="http://schemas.android.com/tools"

推荐