Android中Fragment的用法

Fragment的出现主要是为了解决安卓设备尺寸多样化后界面的显示问题。Fragment比Activity较轻量级,可以提供与用户交互的界面并且有自己的生命周期,也不用在AndroidManifest.xml中注册,但它必须嵌套在Activity中使用。之前需要使用多个Activity显示的内容,现在可以用一个Activity嵌套多个Fragment来实现。

1.静态Fragment的实现

从Demo中来学习是最容易理解的

1.1 先看实现效果

左右两个fragment拼接在一起
在这里插入图片描述

1.2实现过程

1.2.1创建fragment.xml文件(以左边的为例)

在layout下创建fragment.xml文件:

<?xml version="1.0" encoding="utf-8"?>//左边fragment的界面布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button1"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button2"/>

</LinearLayout>

1.2.2新建类继承android.support.v4.app.Fragment

将1.2.1中创建的配置文件通过inflater加载进LeftFragment中

package com.example.fragmenttest;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值