Fragment——小白实训笔记

本文详细介绍了Android中的Fragment,包括其定义、作用、静态及动态加载方法,以及如何结合ViewPager实现页卡滑动切换。适合Android开发初学者,提供完整的代码示例。
摘要由CSDN通过智能技术生成

Fragment

**

*1. 什么是Fragment?


Fragment可以叫为“片段”或“碎片”,表示Activity中的行为或用户界面部分。我们可以在一个Activity中用多个Fragment组合来构建多窗格。

2. 用Fragment解决什么问题?

  • 使用Fragment可以在一个Activity中实现不同界面的灵活切换。
  • 当一款APP同时推出手机版和Pad版,不需要再分别编写多套布局方案,通过Fragment设计的布局可以动态、灵活的解决不同屏幕分辨率的适配问题。
  • 对于小白,想模仿一些APP里底部菜单框实现上面的页面跳转,只能用Activity来实现,这样就会有很繁琐的代码和错误,并且会有页面跳转的痕迹,这时用Fragment就可以很好的解决这一问题。

*3. Fragment静态加载方法(附代码)*

  • Fragment静态加载步骤:

    1)新建类继承Fragement;
    2)重写onCreateView;
    3)使用LayoutInflater对象中的inflate方法绑定布局和控件;
    4)在Activity对应的布局文件中通过<fragment>标签引用。

  • 代码演示:

xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.pc.fragment.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="Hello World!"
        android:textSize="30sp"
        android:gravity="center"
    />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <fragment
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:id="@+id/f_one"
            android:name="com.example.pc.fragment.fragment.Fragmentone"
            />
        <fragment

            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:id="@+id/f_two"
            android:name="com.example.pc.fragment.fragment.Fragmenttwo"
            />
    </LinearLayout>


</LinearLayout>

创建两个Fragment类
Fragment的java代码:

package com.example.pc.fragment.fragment;


import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值