Android Fragment(碎片)的使用

  • 简介
    在Android中Fragment为一种可以嵌入活动中的UI片段.能让程序更加合理地利用大屏幕的空间.
  • 使用方法
    1.我们首先新建的一个onefragment.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:background="#e3e3e3"
    android:orientation="vertical" >
    
    <TextView 
        android:id="@+id/tv_right_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="this is fragment"
        />
</LinearLayout>

2.新建一个OneFragment.class(这里要注意的是,不要继承V4包)

public class OneFrament extends Fragment{

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

3.使用OneFrament

<fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmentdemo.OneFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
  • 动态添加Fragment.
    1.在要添加到的activity.xml布局里面添加.
<FrameLayout
        android:id="@+id/right_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" >
</FrameLayout>

2.在要添加到的activity.class里添加.

AnotherRightFrament frament=new AnotherRightFrament(); //实例化要添加的Fragment
				FragmentManager fragmentManager=getFragmentManager();   //取到FragmentManager.
				FragmentTransaction transaction=fragmentManager.beginTransaction();
				transaction.replace(R.id.right_layout, frament);    //根据ID指定要添加到的FrameLayout
				transaction.commit();
  • 在上面.
    1.创建待添加的碎片实例.
    2.获取到FragmentManager,在活动中可以直接调用getFramentManager()方法得到.
    3.开启一个事务,通过调用beginTransaction()方法开启.
    4.向容器内添加碎片,一般使用replace()方法,需要传入容器的ID和待添加的碎片实例.
    5.提交事务,调用commit()方法来完成.

更......

  • 当我们运行上面的程式,跳转到另一个fragment的时候,习惯性的按下back返回,当却发现程序退出了.这个时候我们就要在碎片中模拟返回栈.
    transaction.addToBackStack(null);
AnotherRightFrament frament=new AnotherRightFrament();
				FragmentManager fragmentManager=getFragmentManager();
				FragmentTransaction transaction=fragmentManager.beginTransaction();
				transaction.replace(R.id.right_layout, frament);
				transaction.addToBackStack(null);
				transaction.commit();

我们在事务提交之前调用了FragmentTransaction的addToBackStack()方法,他可以接受一个名字用于描述返回栈的状态,一般传入null就可以了.

  • 碎片和活动之间进行通信
getFragmentManager().findFragmentById(R.id.one_fragment);    //android提供了这样一种方式,一个类似于findviewbyid()的方法,专门来从布局文件获取fragment的实例.
MainActivity activity=(MainActivity) getActivity();    //android 提供了getactivity()来得到和当前碎片有关的activity实例.
posted @ 2015-12-23 15:51  如梦真心  阅读(579)  评论(0编辑  收藏  举报