Android Fragment的使用

來源:互聯網
上載者:User

標籤:

定義

Fragment可以理解成一個迷你型的活動,同樣可以包含布局,同樣有自己的生命週期。比Activity要輕量級,在程式中做介面跳轉要比Activity快的多。

靜態添加

Fragment可以靜態或者動態添加到Activity中,其中靜態情況下,直接在layout.xml中添加fragment節點,並指定android:name屬性就可以啟動相應的fragment.

動態添加

可以在Activity中通過覆蓋onCreate()函數來動態添加Fragment

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        if (savedInstanceState == null){            getSupportFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit();        }    }

在Fragment中可以通過添加按鈕事件接收器覆蓋當前的fragment:

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View rootView = inflater.inflate(R.layout.fragment_main, container, false);        rootView.findViewById(R.id.btnShowAnotherFragment).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                getFragmentManager().beginTransaction()                        .addToBackStack(null)                        .replace(R.id.container, new AnotherFragment())                        .commit();            }        });

注意,一個靜態添加的Fragment,通過這種動態方法進行替換會造成兩個Fragment在Framelayout中的重疊。

生命週期:

當一個Fragment被另一個fragment啟動的時候會執行oncreate, oncreateview,當返回時會onDestroy銷毀。

啟動別人的這個Fragment則只會執行onDestroyView,並不會執行onDestroy。

Android Fragment的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.