Android Fragment彻底解析,关于碎片你所需知道的一切

咱们都知道,Android上的界面展现都是经过Activity实现的,Activity实在是太经常使用了,我相信你们都已经很是熟悉了,这里就再也不赘述。 html

可是Activity也有它的局限性,一样的界面在手机上显示可能很好看,在平板上就未必了,由于平板的屏幕很是大,手机的界面放在平板上可能会有过度被拉长、控件间距过大等状况。这个时候更好的体验效果是在Activity中嵌入"小Activity",而后每一个"小Activity"又能够拥有本身的布局。所以,咱们今天的主角Fragment登场了。 java

Fragment初探 android

为了让界面能够在平板上更好地展现,Android在3.0版本引入了Fragment(碎片)功能,它很是相似于Activity,能够像Activity同样包含布局。Fragment一般是嵌套在Activity中使用的,如今想象这种场景:有两个Fragment,Fragment 1包含了一个ListView,每行显示一本书的标题。Fragment 2包含了TextView和ImageView,来显示书的详细内容和图片。 ide

若是如今程序运行竖屏模式的平板或手机上,Fragment 1可能嵌入在一个Activity中,而Fragment 2可能嵌入在另外一个Activity中,以下图所示: 布局

而若是如今程序运行在横屏模式的平板上,两个Fragment就能够嵌入在同一个Activity中了,以下图所示: spa

由此能够看出,使用Fragment可让咱们更加充分地利用平板的屏幕空间,下面咱们一块儿来探究下如何使用Fragment。 .net

首先须要注意,Fragment是在3.0版本引入的,若是你使用的是3.0以前的系统,须要先导入android-support-v4的jar包才能使用Fragment功能。 日志

新建一个项目叫作Fragments,而后在layout文件夹下新建一个名为fragment1.xml的布局文件: code

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:background="#00ff00" > 
  5.  
  6.     <TextView 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:text="This is fragment 1" 
  10.         android:textColor="#000000" 
  11.         android:textSize="25sp" /> 
  12.  
  13. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 1"
        android:textColor="#000000"
        android:textSize="25sp" />

</LinearLayout>

能够看到,这个布局文件很是简单,只有一个LinearLayout,里面加入了一个TextView。咱们如法炮制再新建一个fragment2.xml : xml

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:background="#ffff00" > 
  5.  
  6.     <TextView 
  7.         android:layout_width="wrap_content" 
  8.         android:layout_height="wrap_content" 
  9.         android:text="This is fragment 2" 
  10.         android:textColor="#000000" 
  11.         android:textSize="25sp" /> 
  12.  
  13. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff00" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 2"
        android:textColor="#000000"
        android:textSize="25sp" />

</LinearLayout>

而后新建一个类Fragment1,这个类是继承自Fragment的:
  1. public class Fragment1 extends Fragment { 
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  5.         return inflater.inflate(R.layout.fragment1, container, false); 
  6.     } 
  7.  

public class Fragment1 extends Fragment {

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

}

咱们能够看到,这个类也很是简单,主要就是加载了咱们刚刚写好的fragment1.xml布局文件并返回。一样的方法,咱们再写好Fragment2 :
  1. public class Fragment2 extends Fragment { 
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  5.         return inflater.inflate(R.layout.fragment2, container, false); 
  6.     } 
  7.  

public class Fragment2 extends Fragment {

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

}

而后打开或新建activity_main.xml做为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:baselineAligned="false" > 
  5.  
  6.     <fragment 
  7.         android:id="@+id/fragment1" 
  8.         android:name="com.example.fragmentdemo.Fragment1" 
  9.         android:layout_width="0dip" 
  10.         android:layout_height="match_parent" 
  11.         android:layout_weight="1" /> 
  12.  
  13.     <fragment 
  14.         android:id="@+id/fragment2" 
  15.         android:name="com.example.fragmentdemo.Fragment2" 
  16.         android:layout_width="0dip" 
  17.         android:layout_height="match_parent" 
  18.         android:layout_weight="1" /> 
  19.  
  20. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragmentdemo.Fragment1"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragmentdemo.Fragment2"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

最后打开或新建MainActivity做为程序的主Activity,里面的代码很是简单,都是自动生成的:
  1. public class MainActivity extends Activity { 
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) { 
  5.         super.onCreate(savedInstanceState); 
  6.         setContentView(R.layout.activity_main); 
  7.     } 
  8.  

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

}

如今咱们来运行一次程序,就会看到,一个Activity很融洽地包含了两个Fragment,这两个Fragment平分了整个屏幕,效果图以下:

动态添加Fragment

你已经学会了如何在XML中使用Fragment,可是这仅仅是Fragment最简单的功能而已。Fragment真正的强大之处在于能够动态地添加到Activity当中,所以这也是你必需要掌握的东西。当你学会了在程序运行时向Activity添加Fragment,程序的界面就能够定制的更加多样化。下面咱们马上来看看,如何动态添加Fragment。

仍是在上一节代码的基础上修改,打开activity_main.xml,将其中对Fragment的引用都删除,只保留最外层的LinearLayout,并给它添加一个id,由于咱们要动态添加Fragment,不用在XML里添加了,删除后代码以下:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:id="@+id/main_layout" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:baselineAligned="false" > 
  6.  
  7. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >

</LinearLayout>

而后打开MainActivity,修改其中的代码以下所示:
  1. public class MainActivity extends Activity { 
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) { 
  5.         super.onCreate(savedInstanceState); 
  6.         setContentView(R.layout.activity_main); 
  7.         Display display = getWindowManager().getDefaultDisplay(); 
  8.         if (display.getWidth() > display.getHeight()) { 
  9.             Fragment1 fragment1 = new Fragment1(); 
  10.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit(); 
  11.         } else
  12.             Fragment2 fragment2 = new Fragment2(); 
  13.             getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit(); 
  14.         } 
  15.     } 
  16.  

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Display display = getWindowManager().getDefaultDisplay();
		if (display.getWidth() > display.getHeight()) {
			Fragment1 fragment1 = new Fragment1();
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
		} else {
			Fragment2 fragment2 = new Fragment2();
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
		}
	}

}

首先,咱们要获取屏幕的宽度和高度,而后进行判断,若是屏幕宽度大于高度就添加fragment1,若是高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:

1.获取到FragmentManager,在Activity中能够直接经过getFragmentManager获得。

2.开启一个事务,经过调用beginTransaction方法开启。

3.向容器内加入Fragment,通常使用replace方法实现,须要传入容器的id和Fragment的实例。

4.提交事务,调用commit方法提交。

如今运行一下程序,效果以下图所示:

若是你是在使用模拟器运行,按下ctrl + F11切换到竖屏模式。效果以下图所示:

                               

Fragment的生命周期

和Activity同样,Fragment也有本身的生命周期,理解Fragment的生命周期很是重要,咱们经过代码的方式来瞧一瞧Fragment的生命周期是什么样的:

  1. public class Fragment1 extends Fragment { 
  2.     public static final String TAG = "Fragment1"
  3.  
  4.     @Override 
  5.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  6.         Log.d(TAG, "onCreateView"); 
  7.         return inflater.inflate(R.layout.fragment1, container, false); 
  8.     } 
  9.  
  10.     @Override 
  11.     public void onAttach(Activity activity) { 
  12.         super.onAttach(activity); 
  13.         Log.d(TAG, "onAttach"); 
  14.     } 
  15.  
  16.     @Override 
  17.     public void onCreate(Bundle savedInstanceState) { 
  18.         super.onCreate(savedInstanceState); 
  19.         Log.d(TAG, "onCreate"); 
  20.     } 
  21.  
  22.     @Override 
  23.     public void onActivityCreated(Bundle savedInstanceState) { 
  24.         super.onActivityCreated(savedInstanceState); 
  25.         Log.d(TAG, "onActivityCreated"); 
  26.     } 
  27.  
  28.     @Override 
  29.     public void onStart() { 
  30.         super.onStart(); 
  31.         Log.d(TAG, "onStart"); 
  32.     } 
  33.  
  34.     @Override 
  35.     public void onResume() { 
  36.         super.onResume(); 
  37.         Log.d(TAG, "onResume"); 
  38.     } 
  39.  
  40.     @Override 
  41.     public void onPause() { 
  42.         super.onPause(); 
  43.         Log.d(TAG, "onPause"); 
  44.     } 
  45.  
  46.     @Override 
  47.     public void onStop() { 
  48.         super.onStop(); 
  49.         Log.d(TAG, "onStop"); 
  50.     } 
  51.  
  52.     @Override 
  53.     public void onDestroyView() { 
  54.         super.onDestroyView(); 
  55.         Log.d(TAG, "onDestroyView"); 
  56.     } 
  57.  
  58.     @Override 
  59.     public void onDestroy() { 
  60.         super.onDestroy(); 
  61.         Log.d(TAG, "onDestroy"); 
  62.     } 
  63.  
  64.     @Override 
  65.     public void onDetach() { 
  66.         super.onDetach(); 
  67.         Log.d(TAG, "onDetach"); 
  68.     } 
  69.  

public class Fragment1 extends Fragment {
	public static final String TAG = "Fragment1";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d(TAG, "onCreateView");
		return inflater.inflate(R.layout.fragment1, container, false);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		Log.d(TAG, "onAttach");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate");
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.d(TAG, "onActivityCreated");
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "onStart");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.d(TAG, "onStop");
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.d(TAG, "onDestroyView");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

	@Override
	public void onDetach() {
		super.onDetach();
		Log.d(TAG, "onDetach");
	}

}

能够看到,上面的代码在每一个生命周期的方法里都打印了日志,而后咱们来运行一下程序,能够看到打印日志以下:

这时点击一下home键,打印日志以下:

若是你再从新进入进入程序,打印日志以下:

而后点击back键退出程序,打印日志以下:

看到这里,我相信大多数朋友已经很是明白了,由于这和Activity的生命周期太类似了。只是有几个Activity中没有的新方法,这里须要重点介绍一下:

  • onAttach方法:Fragment和Activity创建关联的时候调用。
  • onCreateView方法:为Fragment加载布局时调用。
  • onActivityCreated方法:当Activity中的onCreate方法执行完后调用。
  • onDestroyView方法:Fragment中的布局被移除时调用。
  • onDetach方法:Fragment和Activity解除关联的时候调用。

Fragment之间进行通讯

一般状况下,Activity都会包含多个Fragment,这时多个Fragment之间如何进行通讯就是个很是重要的问题了。咱们经过一个例子来看一下,如何在一个Fragment中去访问另外一个Fragment的视图。

仍是在第一节代码的基础上修改,首先打开fragment2.xml,在这个布局里面添加一个按钮:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:orientation="vertical" 
  5.     android:background="#ffff00" > 
  6.  
  7.     <TextView 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="wrap_content" 
  10.         android:text="This is fragment 2" 
  11.         android:textColor="#000000" 
  12.         android:textSize="25sp" /> 
  13.      
  14.     <Button  
  15.         android:id="@+id/button" 
  16.         android:layout_width="wrap_content" 
  17.         android:layout_height="wrap_content" 
  18.         android:text="Get fragment1 text" 
  19.         /> 
  20.  
  21. </LinearLayout> 

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 2"
        android:textColor="#000000"
        android:textSize="25sp" />
    
    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get fragment1 text"
        />

</LinearLayout>

而后打开fragment1.xml,为TextView添加一个id:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="match_parent" 
  3.     android:layout_height="match_parent" 
  4.     android:background="#00ff00" > 
  5.  
  6.     <TextView 
  7.         android:id="@+id/fragment1_text" 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="wrap_content" 
  10.         android:text="This is fragment 1" 
  11.         android:textColor="#000000" 
  12.         android:textSize="25sp" /> 
  13.  
  14. </LinearLayout> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00" >

    <TextView
        android:id="@+id/fragment1_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is fragment 1"
        android:textColor="#000000"
        android:textSize="25sp" />

</LinearLayout>

接着打开Fragment2.java,添加onActivityCreated方法,并处理按钮的点击事件:
  1. public class Fragment2 extends Fragment { 
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  5.         return inflater.inflate(R.layout.fragment2, container, false); 
  6.     } 
  7.  
  8.     @Override 
  9.     public void onActivityCreated(Bundle savedInstanceState) { 
  10.         super.onActivityCreated(savedInstanceState); 
  11.         Button button = (Button) getActivity().findViewById(R.id.button); 
  12.         button.setOnClickListener(new OnClickListener() { 
  13.             @Override 
  14.             public void onClick(View v) { 
  15.                 TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text); 
  16.                 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show(); 
  17.             } 
  18.         }); 
  19.     } 
  20.  

public class Fragment2 extends Fragment {

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

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Button button = (Button) getActivity().findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
				Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
			}
		});
	}

}

如今运行一下程序,并点击一下fragment2上的按钮,效果以下图所示:

咱们能够看到,在fragment2中成功获取到了fragment1中的视图,并弹出Toast。这是怎么实现的呢?主要都是经过getActivity这个方法实现的。getActivity方法可让Fragment获取到关联的Activity,而后再调用Activity的findViewById方法,就能够获取到和这个Activity关联的其它Fragment的视图了。

好了,以上就是关于Fragment你所须知道的一切。

相关文章
相关标签/搜索