Android類參考—Fragment(二)

上一篇:/kf/201205/134000.html

回退堆棧

在Fragment中被編輯的事務能夠放在它自己的Activity中回退堆棧內。當用戶在該Activity中按下返回按鈕時,在回退堆棧中的任何事務在Activity自己被結束之前會被彈出堆棧。

例如,實例化一個帶有整數參數的簡單的Fragment對象,並且把這個整數顯示在它的UI的一個TextView中:

publicstaticclassCountingFragmentextendsFragment{
    int mNum;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    staticCountingFragment newInstance(int num){
        CountingFragment f =newCountingFragment();

        // Supply num input as an argument.
        Bundle args =newBundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    publicvoid onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        mNum = getArguments()!=null? getArguments().getInt("num"):1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    publicView onCreateView(LayoutInflater inflater,ViewGroup container,
            Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.hello_world, container,false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Fragment #"+ mNum);
        tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
        return v;
    }
}

用下面的方法創建一個新的Fragment實例,用它來替換當前被顯示的Fragment實例,並把這種改變發佈到回退堆棧上:

void addFragmentToStack(){
    mStackLevel++;

    // Instantiate a new fragment.
    Fragment newFragment =CountingFragment.newInstance(mStackLevel);

    // Add the fragment to the activity, pushing this transaction
    // on to the back stack.
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.simple_fragment, newFragment);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();
}

每次調用上面這個方法之後,就會在堆棧上增加一個新的實體,並且按下回退鍵時,會把它從堆棧中彈出,並給用戶返回之前的Activity狀態。

 

 

摘自 FireOfStar的專欄

發佈留言