Fragment里嵌套Fragment之间的切换

在说例子之前首先了解一些关于Fragment的基本知识,Fragment和Activity的生命周期很相似,实现一个Fragment要重写其OnCreateView方法。

Fragment可以看做是Activity的一部分,可以添加到Activity的任意一个Layout布局中,并随着Activity的销毁而销毁。

为了更好的向低版本兼容一般我们在使用的时候都会采用support.v4下的Fragment。

Fragment的添加采用的是事物的方式,分为以下几步:

1.获得事物

FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();

2.添加Fragment

//R.id.rl_fragment_container是获得的布局文件
beginTransaction.add(R.id.rl_fragment_container, fragmentLeft);

3.提交事物

beginTransaction.commitAllowingStateLoss();


Fratment切换时同样也是采取事物的方式,分为以下几步:

1.获得事物

FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();

2.判断替换的Fragment是否添加到事物中过,如果添加过,那么隐藏之前显示的Fragment显示新的Fragment;如果没有则添加到事物中显示。

之所以采取隐藏而不是替换的方式是因为我们许多的项目中需要切换Fragment时候要求之前的Fragment数据不能清空,方便用户来回切换查看而且也更省流量。

if (!to.isAdded()) { // 先判断是否被add过
	transaction.hide(mFragment)
			.add(R.id.rl_fragment_container, to)
			.commitAllowingStateLoss(); // 隐藏当前的fragment,add下一个到Activity中
		} else {
			transaction.hide(mFragment).show(to)
							.commitAllowingStateLoss(); // 隐藏当前的fragment,显示下一个
				}


好了基本知识说完了,该去看看实际例子的代码了

本例子实现的是一个Activity中嵌套2个Fragment,而其中的一个Fragment中又嵌套2个Fragment。

1.MainActivity.java

import com.example.fragmentswitchdemo.fragment.FragmentLeft;
import com.example.fragmentswitchdemo.fragment.FragmentRight;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends FragmentActivity implements OnClickListener{
	
	private Button[] mTabs;
	private FragmentLeft fragmentLeft;
	private FragmentRight fragmentRight;
	private Fragment mFragment;//标记当前显示的Fragment
	private int currentTabIndex;//button当前选中的索引
	private int index;//选中button的索引值

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去除标题栏
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initfindViewById();
		initFragment();
	}
	
	private void initfindViewById() {
		mTabs = new Button[2];
		mTabs[0] = (Button) findViewById(R.id.btn_tab_clock);
		mTabs[1] = (Button) findViewById(R.id.btn_tab_bell);
		mTabs[0].setOnClickListener(this);
		mTabs[1].setOnClickListener(this);
		
	}
	
	private void initFragment() {
		fragmentLeft = new FragmentLeft();
		fragmentRight = new FragmentRight();
		//开启事物将fragment添加到布局中并提交事物
		FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
		beginTransaction.add(R.id.rl_fragment_container, fragmentLeft);
		beginTransaction.commitAllowingStateLoss();
		mFragment = fragmentLeft;
		currentTabIndex = 0;
		mTabs[currentTabIndex].setSelected(true);//设置默认Fragment的选择器
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tab_clock:
			index = 0;
			if (null == fragmentLeft) {
				fragmentLeft = new FragmentLeft();
			}
			switchContent(fragmentLeft);
			break;
		case R.id.btn_tab_bell:
			index = 1;
			if (null == fragmentLeft) {
				fragmentRight = new FragmentRight();
			}
			switchContent(fragmentRight);
			break;

		default:
			break;
		}
	}
	
	/** 修改显示的内容 不会重新加载(相当于做了缓存处理,切换时仍能有数据显示) **/
	public void switchContent(Fragment to) {
		try {
			if (mFragment != to) {
				FragmentTransaction transaction = getSupportFragmentManager()
						.beginTransaction();
				if (!to.isAdded()) { // 先判断是否被add过
					transaction.hide(mFragment)
							.add(R.id.rl_fragment_container, to)
							.commitAllowingStateLoss(); // 隐藏当前的fragment,add下一个到Activity中
				} else {
					transaction.hide(mFragment).show(to)
							.commitAllowingStateLoss(); // 隐藏当前的fragment,显示下一个
				}
				mFragment = to;
			}
			mTabs[currentTabIndex].setSelected(false);
			// 把当前tab设为选中状态
			mTabs[index].setSelected(true);
			currentTabIndex = index;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

2.布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white" >

    <LinearLayout
        android:id="@+id/ll_bottom_button"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <RelativeLayout
            android:id="@+id/rl_tab_clock"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1" >

            <Button
                android:id="@+id/btn_tab_clock"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                android:drawableTop="@drawable/tab_clock_bg"
                android:paddingBottom="7dip"
                android:paddingTop="2dip"
                android:scaleType="matrix"
                android:text="鲜抢"
                android:textColor="@color/tab_botton_text_color"
                android:textSize="10sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_tab_bell"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1" >

            <Button
                android:id="@+id/btn_tab_bell"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                android:drawableTop="@drawable/tab_bell_bg"
                android:paddingBottom="7dip"
                android:paddingTop="2dip"
                android:scaleType="matrix"
                android:text="我的提醒"
                android:textColor="@color/tab_botton_text_color"
                android:textSize="10sp" />
        </RelativeLayout>
    </LinearLayout>

    <View
        android:id="@+id/view_line1"
        android:layout_width="fill_parent"
        android:layout_height="0.5dp"
        android:layout_above="@id/ll_bottom_button"
        android:background="@color/gray" />

    <RelativeLayout
        android:id="@+id/rl_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/view_line1" />

</RelativeLayout>

3.fragmentRight

import com.example.fragmentswitchdemo.R;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/** 
 * @author quzy 
 *
 * @Description 
 *
 * @version 创建时间:2016-2-25 下午6:04:24
 */
public class FragmentRight extends Fragment{
	
	private View view_fragment;
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreateView(inflater, container, savedInstanceState);
		view_fragment = inflater.inflate(R.layout.fragment_right, null);
		return view_fragment;
	}

}


4.FragmentLeft

package com.example.fragmentswitchdemo.fragment;

import com.example.fragmentswitchdemo.R;
import com.example.fragmentswitchdemo.innerfragment.InnerFragmentLeft;
import com.example.fragmentswitchdemo.innerfragment.InnerFragmentRight;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * @author quzy
 * 
 * @Description
 * 
 * @version 创建时间:2016-2-25 下午5:43:48
 */
public class FragmentLeft extends Fragment implements OnClickListener {

	private View view_fragment;
	private InnerFragmentLeft innerFragmentLeft;
	private InnerFragmentRight innerFragmentRight;
	private Fragment mContent;
	private Button[] mTabs;
	private int currentTabIndex;
	private int index;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreateView(inflater, container, savedInstanceState);
		view_fragment = inflater.inflate(R.layout.fragment_left, null);
		initfindViewById();
		initFragment();
		return view_fragment;
	}

	private void initfindViewById() {
		mTabs = new Button[2];
		mTabs[0] = (Button) view_fragment
				.findViewById(R.id.btn_tab_clock_inner_left);
		mTabs[1] = (Button) view_fragment
				.findViewById(R.id.btn_tab_bell_inner_left);
		mTabs[0].setOnClickListener(this);
		mTabs[1].setOnClickListener(this);
	}

	private void initFragment() {
		innerFragmentLeft = new InnerFragmentLeft();
		innerFragmentRight = new InnerFragmentRight();
		FragmentTransaction beginTransaction = getFragmentManager()
				.beginTransaction();
		beginTransaction
				.add(R.id.rl_left_fragment_container, innerFragmentLeft);
		beginTransaction.commitAllowingStateLoss();
		mContent = innerFragmentLeft;
		currentTabIndex = 0;
		mTabs[currentTabIndex].setSelected(true);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_tab_clock_inner_left:
			index = 0;
			if (null == innerFragmentLeft) {
				innerFragmentLeft = new InnerFragmentLeft();
			}
			switchContent(innerFragmentLeft);
			break;
		case R.id.btn_tab_bell_inner_left:
			index = 1;
			if (null == innerFragmentRight) {
				innerFragmentRight = new InnerFragmentRight();
			}
			switchContent(innerFragmentRight);
			break;
		default:
			break;
		}
	}

	/** 修改显示的内容 不会重新加载 **/
	public void switchContent(Fragment to) {
		try {
			if (mContent != to) {
				FragmentTransaction transaction = getFragmentManager()
						.beginTransaction();
				if (!to.isAdded()) { // 先判断是否被add过
					transaction.hide(mContent)
							.add(R.id.rl_left_fragment_container, to)
							.commitAllowingStateLoss(); // 隐藏当前的fragment,add下一个到Activity中
				} else {
					transaction.hide(mContent).show(to)
							.commitAllowingStateLoss(); // 隐藏当前的fragment,显示下一个
				}
				mContent = to;
			}
			mTabs[currentTabIndex].setSelected(false);
			// 把当前tab设为选中状态
			mTabs[index].setSelected(true);
			currentTabIndex = index;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

5.fragment_left.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white" >
    <LinearLayout
        android:id="@+id/ll_textview_time"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_alignParentTop="true"
        android:background="@color/green" 
        android:gravity="center"
        android:orientation="horizontal" 
        android:padding="5dp">
            <Button
                android:id="@+id/btn_tab_clock_inner_left"
                android:layout_width="85dp"
                android:layout_height="match_parent"
                android:background="@drawable/peisong_button_release"
                android:paddingBottom="7dip"
                android:paddingTop="2dip"
                android:scaleType="matrix"
                android:text="左边"
                android:textSize="12sp" />
            <Button
                android:id="@+id/btn_tab_bell_inner_left"
                android:layout_width="85dp"
                android:layout_height="match_parent"
                android:background="@drawable/ziti_button_release"
                android:paddingBottom="7dip"
                android:paddingTop="2dip"
                android:scaleType="matrix"
                android:text="右边"
                android:textSize="12sp" />
    </LinearLayout>
    
    <RelativeLayout
        android:id="@+id/rl_left_fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/ll_textview_time" />
</RelativeLayout>

以下在FragmentLeft在加入2个Fragment的方法和MainActivity中添加是一样。

部分代码和布局文件我没有贴出来看到不太明白的可以去下载源码看看。


源码地址:http://download.csdn.net/detail/linder_qzy/9447886


你可能感兴趣的:(Fragment里嵌套Fragment之间的切换)