Fragment(1)-简单实现

来源:互联网 发布:java缓存过程面试 编辑:程序博客网 时间:2024/06/16 06:40

关于fragment ,

1.是一个区域的UI,可以绑定自己的Layout。当然,他也可以不在界面中显示,而在后台工作。

2.我们可以在一个Activity里加入多个Fragment,也可以多个Activity重用一个Fragment。

3.它拥有自己的生命周期,同时被它所寄存的Activity的生命周期所影响。当Activity销毁,Fragment也被销毁,当Activity暂停,Fragment也暂停

4.Activity正运行时,我们可以对Fragment进行添加,删除,替换等操作


简单实现

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);    }

ps:代码

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

package com.example.fiest;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
原创粉丝点击