Fragment的進一步使用(一)


爲了記筆記,方便日後參考
1、管理Fragment回退棧

類似與Android系統爲Activity維護一個任務棧,我們也可以通過Activity維護一個回退棧來保存每次Fragment事務發生的變化。如果你將Fragment任務添加到回退棧,當用戶點擊後退按鈕時,將看到上一次的保存的Fragment。一旦Fragment完全從後退棧中彈出,用戶再次點擊後退鍵,則退出當前Activity。


如何添加一個Fragment事務到回退棧:

FragmentTransaction.addToBackStack(String)

下面講解代碼:很明顯一共是3個Fragment和一個Activity.

先看Activity的佈局文件:

<RelativeLayout 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" >  
  
    <FrameLayout  
        android:id="@+id/id_content"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent" >  
    </FrameLayout>  
  
</RelativeLayout>  

注意:FragmLayout只能存放Fragment

不同的Fragment就在這個FrameLayout中顯示。

MainActivity.java

import android.app.Activity;  
import android.app.FragmentManager;  
import android.app.FragmentTransaction;  
import android.os.Bundle;  
import android.view.Window;  
  
public class MainActivity extends Activity  
{  
  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_main);  
  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.add(R.id.id_content, new FragmentOne(),"ONE");  
        tx.commit();  
    }  
  
}  

很簡單,直接將FragmentOne添加到佈局文件中的FrameLayout中,注意這裏並沒有調用FragmentTransaction.addToBackStack(String),因爲我不喜歡在當前顯示時,點擊Back鍵出現白板。而是正確的相應Back鍵,即退出我們的Activity.

下面是FragmentOne

import android.app.Fragment;  
import android.app.FragmentManager;  
import android.app.FragmentTransaction;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
  
public class FragmentOne extends Fragment implements OnClickListener  
{  
  
    private Button mBtn;  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        View view = inflater.inflate(R.layout.fragment_one, container, false);  
        mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);  
        mBtn.setOnClickListener(this);  
        return view;  
    }  
  
    @Override  
    public void onClick(View v)  
    {  
        FragmentTwo fTwo = new FragmentTwo();  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.replace(R.id.id_content, fTwo, "TWO");  
        tx.addToBackStack(null);  
        tx.commit();  
  
    }  
  
}  

我們在點擊FragmentOne中的按鈕時,使用了replace方法,如果你看了前一篇博客,一定記得replace是remove和add的合體,並且如果不添加事務到回退棧,前一個Fragment實例會被銷燬。這裏很明顯,我們調用tx.addToBackStack(null);將當前的事務添加到了回退棧,所以FragmentOne實例不會被銷燬,但是視圖層次依然會被銷燬,即會調用onDestoryView和onCreateView,證據就是:仔細看上面的效果圖,我們在跳轉前在文本框輸入的內容,在用戶Back得到第一個界面的時候不見了。


接下來FragmentTwo

import android.app.Fragment;  
import android.app.FragmentManager;  
import android.app.FragmentTransaction;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
  
public class FragmentTwo extends Fragment implements OnClickListener  
{  
  
    private Button mBtn ;  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        View view = inflater.inflate(R.layout.fragment_two, container, false);  
        mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);  
        mBtn.setOnClickListener(this);  
        return view ;   
    }  
    @Override  
    public void onClick(View v)  
    {  
        FragmentThree fThree = new FragmentThree();  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.hide(this);  
        tx.add(R.id.id_content , fThree, "THREE");  
//      tx.replace(R.id.id_content, fThree, "THREE");  
        tx.addToBackStack(null);  
        tx.commit();  
    }  
  
  
}  

這裏點擊時,我們沒有使用replace,而是先隱藏了當前的Fragment,然後添加了FragmentThree的實例,最後將事務添加到回退棧。這樣做的目的是爲了給大家提供一種方案:如果不希望視圖重繪該怎麼做,請再次仔細看效果圖,我們在FragmentTwo的EditText填寫的內容,用戶Back回來時,數據還在~~~

最後FragmentThree就是簡單的Toast了:

import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
import android.widget.Toast;  
  
public class FragmentThree extends Fragment implements OnClickListener  
{  
  
    private Button mBtn;  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        View view = inflater.inflate(R.layout.fragment_three, container, false);  
        mBtn = (Button) view.findViewById(R.id.id_fragment_three_btn);  
        mBtn.setOnClickListener(this);  
        return view;  
    }  
  
    @Override  
    public void onClick(View v)  
    {  
        Toast.makeText(getActivity(), " i am a btn in Fragment three",  
                Toast.LENGTH_SHORT).show();  
    }  
  
}  

知道Fragment回退棧是怎麼一回事了,以及hide,replace等各自的應用的場景。

這裏極其注意一點:上面的整體代碼不具有任何參考價值,純粹爲了顯示回退棧,在後面講解了Fragment與Activity通信以後,會重構上面的代碼!



2、Fragment與Activity通信

因爲所有的Fragment都是依附於Activity的,所以通信起來並不複雜,大概歸納爲:

a、如果你Activity中包含自己管理的Fragment的引用,可以通過引用直接訪問所有的Fragment的public方法

b、如果Activity中未保存任何Fragment的引用,那麼沒關係,每個Fragment都有一個唯一的TAG或者ID,可以通過getFragmentManager.findFragmentByTag()或者findFragmentById()獲得任何Fragment實例,然後進行操作。

c、在Fragment中可以通過getActivity得到當前綁定的Activity的實例,然後進行操作。

注:如果在Fragment中需要Context,可以通過調用getActivity(),如果該Context需要在Activity被銷燬後還存在,則使用getActivity().getApplicationContext()。

3、Fragment與Activity通信的最佳實踐

因爲要考慮Fragment的重複使用,所以必須降低Fragment與Activity的耦合,而且Fragment更不應該直接操作別的Fragment,畢竟Fragment操作應該由它的管理者Activity來決定


下面我通過兩種種方式的代碼,分別重構,FragmentOne和FragmentTwo的點擊事件,以及Activity對點擊事件的響應:

首先看FragmentOne

package com.zhy.zhy_fragments;  
  
import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
  
public class FragmentOne extends Fragment implements OnClickListener  
{  
    private Button mBtn;  
  
    /** 
     * 設置按鈕點擊的回調 
     * @author zhy 
     * 
     */  
    public interface FOneBtnClickListener  
    {  
        void onFOneBtnClick();  
    }  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        View view = inflater.inflate(R.layout.fragment_one, container, false);  
        mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);  
        mBtn.setOnClickListener(this);  
        return view;  
    }  
  
    /** 
     * 交給宿主Activity處理,如果它希望處理 
     */  
    @Override  
    public void onClick(View v)  
    {  
        if (getActivity() instanceof FOneBtnClickListener)  
        {  
            ((FOneBtnClickListener) getActivity()).onFOneBtnClick();  
        }  
    }  
  
}  

可以看到現在的FragmentOne不和任何Activity耦合,任何Activity都可以使用;並且我們聲明瞭一個接口,來回調其點擊事件,想要管理其點擊事件的Activity實現此接口就即可。可以看到我們在onClick中首先判斷了當前綁定的Activity是否實現了該接口,如果實現了則調用。

再看FragmentTwo

import android.app.Fragment;  
import android.os.Bundle;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.ViewGroup;  
import android.widget.Button;  
  
public class FragmentTwo extends Fragment implements OnClickListener  
{  
  
      
    private Button mBtn ;  
      
    private FTwoBtnClickListener fTwoBtnClickListener ;  
      
    public interface FTwoBtnClickListener  
    {  
        void onFTwoBtnClick();  
    }  
    //設置回調接口  
    public void setfTwoBtnClickListener(FTwoBtnClickListener fTwoBtnClickListener)  
    {  
        this.fTwoBtnClickListener = fTwoBtnClickListener;  
    }  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState)  
    {  
        View view = inflater.inflate(R.layout.fragment_two, container, false);  
        mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);  
        mBtn.setOnClickListener(this);  
        return view ;   
    }  
    @Override  
    public void onClick(View v)  
    {  
        if(fTwoBtnClickListener != null)  
        {  
            fTwoBtnClickListener.onFTwoBtnClick();  
        }  
    }  
  
}  

與FragmentOne極其類似,但是我們提供了setListener這樣的方法,意味着Activity不僅需要實現該接口,還必須顯示調用mFTwo.setfTwoBtnClickListener(this)。

最後看Activity :

import android.app.Activity;  
import android.app.FragmentManager;  
import android.app.FragmentTransaction;  
import android.os.Bundle;  
import android.view.Window;  
  
import com.zhy.zhy_fragments.FragmentOne.FOneBtnClickListener;  
import com.zhy.zhy_fragments.FragmentTwo.FTwoBtnClickListener;  
  
public class MainActivity extends Activity implements FOneBtnClickListener,  
        FTwoBtnClickListener  
{  
  
    private FragmentOne mFOne;  
    private FragmentTwo mFTwo;  
    private FragmentThree mFThree;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_main);  
  
        mFOne = new FragmentOne();  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.add(R.id.id_content, mFOne, "ONE");  
        tx.commit();  
    }  
  
    /** 
     * FragmentOne 按鈕點擊時的回調 
     */  
    @Override  
    public void onFOneBtnClick()  
    {  
  
        if (mFTwo == null)  
        {  
            mFTwo = new FragmentTwo();  
            mFTwo.setfTwoBtnClickListener(this);  
        }  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.replace(R.id.id_content, mFTwo, "TWO");  
        tx.addToBackStack(null);  
        tx.commit();  
    }  
  
    /** 
     * FragmentTwo 按鈕點擊時的回調 
     */  
    @Override  
    public void onFTwoBtnClick()  
    {  
        if (mFThree == null)  
        {  
            mFThree = new FragmentThree();  
  
        }  
        FragmentManager fm = getFragmentManager();  
        FragmentTransaction tx = fm.beginTransaction();  
        tx.hide(mFTwo);  
        tx.add(R.id.id_content, mFThree, "THREE");  
        // tx.replace(R.id.id_content, fThree, "THREE");  
        tx.addToBackStack(null);  
        tx.commit();  
    }  
  
}  

代碼重構結束,與開始的效果一模一樣。上面兩種通信方式都是值得推薦的,隨便選擇一種自己喜歡的。這裏再提一下:雖然Fragment和Activity可以通過getActivity與findFragmentByTag或者findFragmentById,進行任何操作,甚至在Fragment裏面操作另外的Fragment,但是沒有特殊理由是絕對不提倡的。Activity擔任的是Fragment間類似總線一樣的角色,應當由它決定Fragment如何操作。另外雖然Fragment不能響應Intent打開,但是Activity可以,Activity可以接收Intent,然後根據參數判斷顯示哪個Fragment。

轉載自:http://blog.csdn.net/lmj623565791/article/details/37992017

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章