如何从XML定义片段的布局? [英] How can I define a fragment's layout from XML?

查看:155
本文介绍了如何从XML定义片段的布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用XML定义片段的布局,就像我定义视图布局一样。

I'm trying to define a fragment's layout in XML in the same way that I defined the layout of my view.

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

Is this possible? I tried several things, but none of them seem to work.

我的活动布局如下(main.xml):

My activity layout looks as follows (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):

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):

  <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定义片段的布局?

Am I doing something wrong? How can I define the layout of a fragment through XML?

推荐答案

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

A Fragment works much like an activity, in that you need a Java class file to go with it. you cannot create a Fragment just by creating a fragment layout - you need a class for your fragment:


  1. 创建布局XML和Activity子类您的活动

  2. 为您的片段创建布局XML和Fragment子类

  3. 在Activity布局XML中将两者绑定在一起(或者如果使用FragmentTransaction,则使用FragmentTransaction你想用Java代码做到这一点)

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

If you haven't already done so, read, re-read and digest everything on this page: https://developer.android.com/guide/components/fragments.html

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

There's a lot there, but Fragments are an essential part of Android apps now so it's required reading. The good news is that the basics of fragments is pretty simple.

这篇关于如何从XML定义片段的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆