Android-Fragment(1)简单实现

本文介绍了Android中Fragment的基本概念和使用,包括其作为UI区域的性质,能在Activity中添加、删除和替换,并详细阐述了Fragment的生命周期,以及如何在布局文件中添加Fragment和实现OnCreateView方法。
摘要由CSDN通过智能技术生成

1. 前言

关于fragment

  1. 它是一个区域的UI,可以绑定自己的Layout。当然,他也可以不在界面中显示,而在后台工作。
  2. 我们可以在一个Activity里加入多个Fragment,也可以多个Activity重用一个Fragment。
  3. 它拥有自己的生命周期,同时被它所寄存的Activity的生命周期所影响。当Activity销毁,Fragment也被销毁,当Activity暂停,Fragment也暂停
  4. Activity正运行时,我们可以对Fragment进行添加,删除,替换等操作

2. 实现步骤

  1. 在main_activity.xml中添加Fragment的layout,跳出提示框:建立继承自Fragment的子类,
    选择Create New
  2. 在类中添加必要Fragment必要的生命周期方法

    • OnCreateView:在Fragment第一次绘制用户界面,调用此方法,传入它所对应的layout
    • OnCreate:创建Fragment调用此方法
    • OnPause:用户离开调用

    这里我只是简单地实现OnCreateView方法,将Layout绑定

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.first,container,false);
    }

3. 例子

  • first.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is fragment" />

</FrameLayout>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.fiest.MainActivity" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fiest.first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="88dp"
        android:layout_marginTop="172dp"
        android:layout_toRightOf="@+id/textView1" />

</RelativeLayout>

First.Activity

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class first extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.first,container,false);
    }

}

到这里,基本就差不多了,下一篇讲述如何在Activity里实现Fragment的创建,删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值