Android類參考---Fragment(二)

來源:互聯網
上載者:User

上一篇:http://www.bkjia.com/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的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.