第十一课:UI Elements:Fragments(基于AndroidStudio3.2)

本文介绍了Android中Fragment的概念和使用,旨在解决不同屏幕尺寸的适配问题。通过创建Fragment类和布局资源,然后在Activity中添加、替换和移除Fragment。详细讲解了Fragment的生命周期,并提供了静态和动态添加Fragment的示例,帮助开发者更好地理解和运用Fragment。
摘要由CSDN通过智能技术生成

运行Android APP的设备繁多,屏幕大小更是多种多样。针对不同屏幕尺寸,通常情况下,开发者都是先针对手机开发一套源代码,然后拷贝一份,修改布局以适应大屏幕设备,或平板,电视等。为了决解这样的麻烦,Google推出了Fragment。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。

Fragment是一个非常先进的概念,初学程序员可能会接近它惶恐不安,但背后的基本概念很简单。 如果我们将某项活动视为一项活动,我们用户界面的组合单元,将Fragment视为迷你活动 - 它是一个较小的组合单元。 您通常会在运行时显示(并隐藏)Fragment以响应某些内容用户做了; 例如,倾斜设备,从纵向切换到横向,从而提供更多的屏幕空间。 您甚至可以使用片段作为策略适应设备外形; 当应用程序在较小的屏幕上运行时,您将只显示一些Fragment。

Fragment与activity一样,由两部分组成 - Java程序和布局文件。 这个想法几乎相同:在XML文件中定义UI元素,然后在Java程序中实现XML文件,以便XML中的所有视图对象都将成为Java对象。 之后,我们可以使用R.class引用XML中的每个视图对象。 一旦我们围绕这个概念包裹我们的大脑,只需将片段视为普通视图对象,我们可以拖放到主布局文件上 - 当然,片段不是普通视图(但它们是视图)。

The following workflow summarizes the steps on how to get started using Fragments. We will explore them in more detail in the demo project.
1.  Create an Activity
2.  Create a Fragment class (Java file) and a fragment layout resource (XML file)
3.  In the fragment layout resource, compose the UI by dragging and dropping view elements in it—like how we do it in an activity 
resource file
4.  In the Fragment class, override the onCreateViewmethod and inflate the XML file
5.  To add the fragment to the activity statically, add a fragment element to activity_mainand associate this element to Fragment class

6.  To add the fragment during runtime;
a.  In the activity_mainlayout file, insert a ViewGroup object that will act as a placeholder for the fragment
b.  In MainActivity.java, create an instance of the Fragment classc.  Get a FragmentManagerobject; the getManager()method of the 
Activity class should do that
d.  Get a FragmentTransactionobject by calling the beginTransaction()method of the fragment manager
e.  Add the fragment to the activity by calling the add()method of the transaction object

一、Fragment的生命周期

Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。官网这张图很好的说明了两者生命周期的关系:

可以看到Fragment比Activity多了几个额外的生命周期回调方法:
onAttach(Activity)当Fragment与Activity发生关联时调用。
onCreateView(LayoutInflater, ViewGroup,Bundle)创建该Fragment的视图
onActivityCreated(Bundle)当Activity的onCreate方法返回时调用
onDestoryView()与onCreateView想对应,当该Fragment的视图被移除时调用
onDetach()与onAttach相对应,当Fragment与Activity关联被取消时调用
注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现

二、测试一

1、创建一个Fragments的新项目

2、从主菜单栏File ➤ New ➤ Java class,创建一个新类。 将其命名为FragmentA并扩展Fragment类。 确保它与MainActivity类位于同一个包中。

注意:当你输入代码片段扩展Fragment时,AS3会建议两种可能包裹。 一个是android.app.Fragment(这是我们想要的),另一个是androi

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值