您的位置:首页 > 移动开发 > Android开发

android学习日记(一):Fragment详解

2015-12-30 22:14 507 查看

一.Fragment的介绍:

为了界面在不同的屏幕尺寸下都能给用户完美的体验,android在3.0版本之后引入了Fragment功能, 通过使用fragment可以让一个app同时适应手机和平板。我们可以把Fragment看成是Activity界面的一个组成部分,另外Fragment拥有自己的生命周期和接收,处理用户的事件。 更重要的是,我们可以动态的添加,删除和替换某个Fragment。

但是Fragment不能单独的存在,它必须嵌入Activity中。而且Fragment的生命周期直接受所在的Activity影响,比如当activity暂停时,它拥有的所有fragment都暂停,activity销毁时,它拥有的所有fragment都销毁。

当向activity中添加一个Fragment时,它须置于ViewGroup控件中,并且需定义Fragment自己的界面。你可以在layoutxml文件中声明Fragment;也可以在代码中创建Fragment,然后把它加入到ViewGroup控件中。然而,Fragment不一定非要放在activity的界面中,它可以隐藏在后台为actvitiy工作。

二.Fragment的生命周期:

Fragment的生命周期以及和Activity生命周期的关系如下图所示:





onAttach(Activity):

当Fragment与Activity发生关联时调用

onCreateView(LayoutInflater, ViewGroup,Bundle):

为Fragment加载布局时调用,这个方法必须返回frament的layout的根控件

onActivityCreated(Bundle):

当Activity的onCreate方法执行完后调用

onDestoryView():

当该Fragment的布局被移除时调用

onDetach():

当Fragment与Activity关联被取消时调用

大多数程序最少需要对Fragment实现onCeate,onCreateView,以及onPause方法

注意:除了onCreateView,其他方法如果重写,必须调用父类对于该方法的实现

三.Fragment的使用

1.静态的添加Fragment:

a.新建布局文件fragment1.xml:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
android:background="#00ff00">
 <TextView
 android:id="@+id/tv_fragment1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="这是Fragment1"
 android:textSize="25sp"
 />

</LinearLayout>


b.布局文件fragment2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
android:background="#ffff00">
 <TextView
 android:id="@+id/tv_fragment2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="这是Fragment2"
 android:textSize="25sp"
 />

</LinearLayout>


c.新建类Fragment1继承Fragment:

package com.liujian.fragmentdemo;

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

public class Fragment1 extends Fragment {
	//onCreateView周期方法用来加载界面布局
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	return inflater.inflate(R.layout.fragment1, container,false);
}
}


d.新建类Fragment2继承Fragment,代码同上,把R.layout,fragment1改成R.layout.fragment2

e.主Activity的布局文件main_activity.xml:

<LinearLayout 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:orientation="horizontal"
tools:context=".MainActivity" 
android:baselineAligned="false">

<fragment
android:id="@+id/fragment1"
android:name="com.liujian.fragmentdemo.Fragment1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<fragment
android:id="@+id/fragment2"
android:name="com.liujian.fragmentdemo.Fragment2"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"/>
</LinearLayout>


编译得来的效果图如下:






2.动态的添加Fragment

动态的增加删除,替换Fragment是开发中最常用的

a.基于上面代码的基础上,main_activity.xml删除所以对fragment的引用,并且给linearlayout添加id

<pre name="code" class="html"><LinearLayout 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:orientation="horizontal"
tools:context=".MainActivity" 
android:id="@+id/main_activity"
android:baselineAligned="false">


</LinearLayout>


b.主Activty代码:


public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display=getWindowManager().getDefaultDisplay();
FragmentManager manager=getFragmentManager();
//当屏幕宽度大于高度时,添加fragment1,当屏幕高度大于宽度时添加fragment2
if(display.getWidth()>display.getHeight()){ 
	Fragment1 fragment1=new Fragment1();
	manager.beginTransaction().replace(R.id.main_activity,fragment1).commit(); 
}else{
	Fragment2 fragment2=new Fragment2();
	manager.beginTransaction().replace(R.id.main_activity, fragment2).commit();
}
}
}
效果图如下:








动态添加Fragment主要分为四步:

1.得到FragmentManager对象,在Activity中通过getFragmentManager方法得到

2.开始事务,通过beginTransaction方法

3.通过replace方法向容器中添加fragment,第一个参数为容器的id,第二个参数为Fragment对象

4.通过commit方法提交事务



四.Fragment的通信:

所谓fragment的通信,j就是同一个activity中的fragment可以相互得到彼此之间的信息

代码演示如下(在静态添加Fragment的代码基础上修改):

1.在fragment2中添加一个button按钮,设置id为button

2.Fragment2:



<span style="font-size:14px;">public class Fragment2 extends Fragment {
	private TextView textview;
	private Button button;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	return inflater.inflate(R.layout.fragment2, container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onActivityCreated(savedInstanceState);
textview=(TextView) getActivity().findViewById(R.id.tv_fragment1);
button=(Button) getActivity().findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Toast.makeText(getActivity(), textview.getText(),0).show();
			}
		});
}
}</span>
效果图如下:




Fragment通信主要是通过getActivity方法得到所在的Activity对象来实现对其他fragment的内容的调用。另外,Activity通过getFragmentManager.findFragmentByTag()或者findFragmentById()获得任何Fragment实例,然后进行操作

这些差不多就是Fragment的知识点了,下一节开始学习Fragment的实战部分




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: