【问题标题】:How can I define a fragment's layout from XML?如何从 XML 定义片段的布局?
【发布时间】:2012-03-16 06:45:43
【问题描述】:

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

这可能吗?我尝试了几件事,但似乎都没有工作。

我的活动布局如下(main.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 定义片段的布局?

【问题讨论】:

    标签: java android xml


    【解决方案1】:

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

    1. 为您的活动创建布局 XML 和活动子类
    2. 为您的片段创建布局 XML 和片段子类
    3. 在您的 Activity 布局 XML 中将两者联系在一起(或者如果您想在 Java 代码中使用 FragmentTransaction)

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

    那里有很多,但片段现在是 Android 应用程序的重要组成部分,因此需要阅读。好消息是片段的基础非常简单。

    【讨论】:

    • 它们不是严格要求的,但在许多情况下它们会让您的生活更轻松。
    • 当前自动生成的 Eclipse 示例使用 FragmentTransactions 我认为......视图由静态片段类生成并从功能调用返回。我目前正在研究如何添加自己的标签。
    • Fragment 类的实例如何指定哪个 XML 文件包含其布局? ActivitysetContentView(R.layout.my_activity_layout),可以在onCreate()期间调用。有片段的类似物吗?
    【解决方案2】:

    只需添加到您的&lt;fragment&gt; 标签中作为属性:

    tools:layout="@layout/your_layout_xml"
    

    并在您的 main.xml(或 &lt;fragment&gt; 标签容器)中放入您的父容器(在本例中为 ListView):

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

    【讨论】:

    • tools:layout 仅用于编辑器预览,与实际使用的布局无关。
    • 虽然这个答案与 OP 的问题没有直接关系,但它对我的工作绝对有帮助。谢谢!
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多