[英]How can I define a fragment's layout from XML?
I'm trying to define a fragment's layout in XML in the same way that I defined the layout of my view. 我正在尝试用XML定义片段的布局,就像我定义视图布局一样。
Is this possible? 这可能吗? I tried several things, but none of them seem to work.
我尝试了几件事,但似乎都没有。
My activity layout looks as follows (main.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>
Now, since I'm not a big fan of generating layouts through raw Java code, I tried defining my fragment as follows (fragment_lommeregner.xml): 现在,由于我不是通过原始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>
Am I doing something wrong? 难道我做错了什么? How can I define the layout of a fragment through XML?
如何通过XML定义片段的布局?
A Fragment works much like an activity, in that you need a Java class file to go with it. Fragment的工作方式与活动非常相似,因为您需要一个Java类文件。 you cannot create a Fragment just by creating a fragment layout - you need a class for your fragment:
你不能仅仅通过创建片段布局来创建片段 - 你需要一个片段类:
If you haven't already done so, read, re-read and digest everything on this page: https://developer.android.com/guide/components/fragments.html 如果您还没有这样做,请阅读,重新阅读并摘要此页面上的所有内容: https : //developer.android.com/guide/components/fragments.html
There's a lot there, but Fragments are an essential part of Android apps now so it's required reading. 那里有很多,但片段是Android应用程序的重要组成部分,所以它需要阅读。 The good news is that the basics of fragments is pretty simple.
好消息是碎片的基础非常简单。
Simply add into your <fragment>
tag as property: 只需将
<fragment>
标记作为属性添加到:
tools:layout="@layout/your_layout_xml"
And in your main.xml (or <fragment>
tag container) into your parent container (in this case ListView
): 并在您的main.xml(或
<fragment>
标签容器)中放入您的父容器(在本例中为ListView
):
xmlns:tools="http://schemas.android.com/tools"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.