Fragment使用方法一则

之前在项目里也用到了fragment,作为横向滑动的组件显示不同栏目的内容,感觉和activity很类似,也就一直没有多发心思在上面。今天看到一个demo算是把我过去的一些猜想验证了。直接放代码

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.replace(R.id.head, new HeadFragment());//将制定的view替换为fragment对象
		ft.replace(R.id.bottom, new BottomFragment());
		ft.add(new HeadFragment(), "head");//通过"head"可以从stack中取出对应的fragment 这在之前项目里没有用到
		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);//切换动画
		ft.commit();//提交

 布局文件

<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="vertical"
    tools:context=".FragmemtActivity" >

    <LinearLayout
        android:id="@+id/head"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
    </LinearLayout>

</LinearLayout>

以下是某个fragment

public class HeadFragment extends Fragment{

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View contentView = inflater.inflate(R.layout.head, null);
		container.addView(contentView);
		return super.onCreateView(inflater, container, savedInstanceState);
	}
	
}

 fragmeng的布局文件

<?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" >
    <TextView android:id="@+id/txt_head" android:text="head" android:layout_width="fill_parent" android:layout_height="wrap_content"/>

</LinearLayout>

最让我惊讶的是fragment替换了指定的view

猜你喜欢

转载自wiseideal.iteye.com/blog/1807483