天天看點

Fragment實作底部菜單欄以及頁籤之間的切換

       相信大家對Fragment(碎片)已經不是那麼陌生了,我們做頁籤一般是用TabActivity和TabHost來做,但是在4.0以後你會發現當你用TabActivity的時候它被畫了一個橫杠,因為它被棄用了。既然它被棄用了,那麼用什麼來代替它呢?這個時候Fragment就出現了,Fragment是在Android3.0以後出現,它就能代替TabActivity。說到Fragment我得提醒一下,當用開始事務時添加Fragment我建議用add()方法添加,不要用replace()來替換Fragment,因為用add()添加的話就可以儲存這個Fragment了,進而Fragment中的資料就不會丢失了,如果你用replace()來替換的話,每次都相當于打開一個新的Fragment,這樣的話每次都要重新添加一次資料,這樣體驗的效果就不是很好了。我當時就遇到這個問題,糾結了好久啊,結果把replace()換成add()問題順利解決。

如果不知道Fragment怎麼使用可以參照:http://blog.csdn.net/yangyu20121224/article/details/8989063    

                                                                  http://www.cnblogs.com/TerryBlog/archive/2012/02/17/2355753.html 

其實給我的感覺Fragment就相當于一個元件。

一、實作的效果圖

Fragment實作底部菜單欄以及頁籤之間的切換
Fragment實作底部菜單欄以及頁籤之間的切換

二、工程結構目錄

Fragment實作底部菜單欄以及頁籤之間的切換

三、具體編碼的實作

MainActivity的布局檔案:activity_main.xml

其實很簡單,底部四個按鈕,上邊部分用一個FrameLayout布局先把位置給占着,放Fragment

<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" >

    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </FrameLayout>

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/maintab_toolbar_bg"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/ll_home"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/btn_selector"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/image_home"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/home_btn_selector" />

            <TextView
                android:id="@+id/text_home"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="首頁"
                android:textColor="@android:color/white" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_friends"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/btn_selector"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/image_friends"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/friends_btn_selector" />

            <TextView
                android:id="@+id/text_friends"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="好友"
                android:textColor="@android:color/white" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/btn_selector"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/image_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/message_btn_selector" />

            <TextView
                android:id="@+id/text_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="資訊"
                android:textColor="@android:color/white" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll_more"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/btn_selector"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/image_more"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/more_btn_selector" />

            <TextView
                android:id="@+id/text_more"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="更多"
                android:textColor="@android:color/white" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
           

 Fragment的布局檔案:fragment_1.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="@drawable/home_bg">

    
</LinearLayout>
           

現在我們來主要來看一下首頁面的代碼,這裡添加Fragment的時候一定要注意,必須要用add()方法添加,這樣才能儲存資料;

如果用replace()替換的話,當第二次打開時資料将不會被儲存。

MainActivity.java

package com.hua.fragmentdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends FragmentActivity implements OnClickListener{
	private LinearLayout ll_home;
	private LinearLayout ll_friends;
	private LinearLayout ll_message;
	private LinearLayout ll_more;
	private ImageView image_home;
	private ImageView image_friends;
	private ImageView image_message;
	private ImageView image_more;
	//Fragment管理器
	private FragmentManager fm = this.getSupportFragmentManager();
	private FragmentTransaction ft;
	private FragmentPage1 fragmentPage1;
	private FragmentPage2 fragmentPage2;
	private FragmentPage3 fragmentPage3;
	private FragmentPage4 fragmentPage4;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();
		//開始事務(每次改變Fragment管理器之後都要送出)
		ft = fm.beginTransaction();
		home();
		//送出事務
		ft.commit();
	}

	private void initView(){
		ll_home = (LinearLayout)findViewById(R.id.ll_home);
		ll_friends = (LinearLayout)findViewById(R.id.ll_friends);
		ll_message = (LinearLayout)findViewById(R.id.ll_message);
		ll_more = (LinearLayout)findViewById(R.id.ll_more);
		
		image_home = (ImageView)findViewById(R.id.image_home);
		image_friends = (ImageView)findViewById(R.id.image_friends);
		image_message = (ImageView)findViewById(R.id.image_message);
		image_more = (ImageView)findViewById(R.id.image_more);
		
		ll_home.setOnClickListener(this);
		ll_friends.setOnClickListener(this);
		ll_message.setOnClickListener(this);
		ll_more.setOnClickListener(this);
		ll_home.setSelected(true);
		image_home.setSelected(true);
		
	}
	
	@Override
	public void onClick(View v) {
		//每次點選時都需要重新開始事務
		ft = fm.beginTransaction();
		//把顯示的Fragment隐藏
		setSelected();
		switch (v.getId()) {
		case R.id.ll_home:
			ll_home.setSelected(true);
			image_home.setSelected(true);
			home();
			break;
		case R.id.ll_friends:
			ll_friends.setSelected(true);
			image_friends.setSelected(true);
			friend();
			
			break;
		case R.id.ll_message:
			ll_message.setSelected(true);
			image_message.setSelected(true);
			message();
			break;
		case R.id.ll_more:
			ll_more.setSelected(true);
			image_more.setSelected(true);
			more();
			break;
		}
		ft.commit();
		
	}
	
	private void setSelected(){
		ll_home.setSelected(false);
		ll_friends.setSelected(false);
		ll_message.setSelected(false);
		ll_more.setSelected(false);
		image_home.setSelected(false);
		image_friends.setSelected(false);
		image_message.setSelected(false);
		image_more.setSelected(false);
		if(fragmentPage1 != null){
			//隐藏Fragment
			ft.hide(fragmentPage1);
		}
		if(fragmentPage2 != null){
			ft.hide(fragmentPage2);
		}
		if(fragmentPage3 != null){
			ft.hide(fragmentPage3);
		}
		if(fragmentPage4 != null){
			ft.hide(fragmentPage4);
		}
	}

	private void home(){
		if(fragmentPage1 == null){
			fragmentPage1 = new FragmentPage1();
			/*添加到Fragment管理器中
			這裡如果用replace,
			當每次調用時都會把前一個Fragment給幹掉,
			這樣就導緻了每一次都要建立、銷毀,
			資料就很難儲存,用add就不存在這樣的問題了,
			當Fragment存在時候就讓它顯示,不存在時就建立,
			這樣的話資料就不需要自己儲存了,
			因為第一次建立的時候就已經儲存了,
			隻要不銷毀一直都将存在*/
			ft.add(R.id.fl_content, fragmentPage1);
		}else{
			//顯示Fragment
			ft.show(fragmentPage1);
		}
	}
	private void friend(){
		if(fragmentPage2 == null){
			fragmentPage2 = new FragmentPage2();
			ft.add(R.id.fl_content, fragmentPage2);
		}else{
			ft.show(fragmentPage2);
		}
		
	}
	private void message(){
		if(fragmentPage3 == null){
			fragmentPage3 = new FragmentPage3();
			ft.add(R.id.fl_content, fragmentPage3);
		}else{
			ft.show(fragmentPage3);
		}
		
	}
	private void more(){
		if(fragmentPage4 == null){
			fragmentPage4 = new FragmentPage4();
			ft.add(R.id.fl_content, fragmentPage4);
		}else{
			ft.show(fragmentPage4);
		}
		
	}
}

           

Fragment的代碼,這裡我把它的生命周期裡的方法列印了一下,友善看到Fragment在什麼時候建立、什麼時候銷毀。用add()和用replace()時候生命周期的變化。

其實我感覺吧,這裡面我一般隻用這幾個方法onCreateView(),onActivityCreated(),onAttach(),其它我都沒有用過。

FragmentPage1.java

package com.hua.fragmentdemo;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentPage1 extends Fragment{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i("TAG", "---onCreateView");
		return inflater.inflate(R.layout.fragment_1, null);		
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.i("TAG", "---onActivityCreated");
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		Log.i("TAG", "---onAttach");
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i("TAG", "---onCreate");
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		Log.i("TAG", "---onDestroy");
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onPause() {
		Log.i("TAG", "---onPause");
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onResume() {
		Log.i("TAG", "---onResume");
		// TODO Auto-generated method stub
		super.onResume();
	}
}
           

文章到這就完了,這是我第一次寫,寫得不好還請大家不要見諒,同時也歡迎大家提出寶貴意見共同探讨一下。

源碼下載下傳位址

繼續閱讀