Android UI開發第三十篇——使用Fragment構建靈活的案頭

來源:互聯網
上載者:User

          當我們設計應用程式時,希望能夠盡最大限度的適配各種裝置,包括4寸屏、7寸屏、10寸屏等等,Android開發文檔給了我們參考,而且Google IO的app(二)也實現了這種思想,他們都是使用layout、layout-large裡面不同的布局檔案實現的,下面是翻譯的developer.android.com一篇的文章,裡面的例子能詳細的看出layout、layout-large並使用Fragmen構建靈活的案頭。

         當設計應用程式,你可以在不同的布局結構中重複使用Fragment,以支援眾多的螢幕尺寸,,在可用的螢幕空間上最佳化使用者體驗。例如在手持功能(如Nexus 4)上,一個屏顯示一個Fragment,在更大屏(如Nexus 7)上可以使用多個Fragment顯示資訊。如:


圖一

         圖一中,在大屏中兩個Fragment顯示在一個屏中,但是手持功能中,需要兩屏顯示完,一屏只能顯示一個,他們之間需要相互引導。

         FragmentManager類提供了一些方法,使您可以在Activity運行時添加,刪除和替換Fragment,以創造一個靈活、動態體驗。

添加Fragment到一個啟動並執行Activity

         這裡不是如同 《

Android UI開發第十七篇——Android Fragment執行個體》中將<fragment>標籤放到布局檔案。而是使用FragmentManager動態管理Fragment。FragmentManager建立一個FragmentTransaction,

它提供了添加,刪除以及其他fragment事務的API。activity允許移除或者替換fragment需要有如下條件:

  1、activity的onCreate()方法中添加初始化的fragment

  2、fragment置放位置的布局中必須有一個視圖容器

程式例子中, res/layout/news_articles.xml檔案提供了視圖容器。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/fragment_container"    android:layout_width="match_parent"    android:layout_height="match_parent" />

    Activity中使用getSupportFragmentManager()擷取FragmentManager,之後調用beginTransaction去建立一個FragmentTransaction對象, 再調用add()方法即可添加一個fragment。 在activity中可以使用同一個FragmentTransaction對象去執行多個fragment事務,當做這樣操作時,必須調用commint()方法。 下面的代碼示範怎樣添加一個fragment到res/layout/news_articles.xml的layout:

import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.news_articles);        // Check that the activity is using the layout version with        // the fragment_container FrameLayout        if (findViewById(R.id.fragment_container) != null) {            // However, if we're being restored from a previous state,            // then we don't need to do anything and should return or else            // we could end up with overlapping fragments.            if (savedInstanceState != null) {                return;            }            // Create an instance of ExampleFragment            HeadlinesFragment firstFragment = new HeadlinesFragment();                        // In case this activity was started with special instructions from an Intent,            // pass the Intent's extras to the fragment as arguments            firstFragment.setArguments(getIntent().getExtras());                        // Add the fragment to the 'fragment_container' FrameLayout            getSupportFragmentManager().beginTransaction()                    .add(R.id.fragment_container, firstFragment).commit();        }    }}

    這裡的fragment是在運行時添加到FrameLayout,而不是直接使用<fragment>標籤定義在activity的布局中,activity可以移除它或者使用另外一個不同的fragment替換它。


替換Fragment

    替換一個fragment的過程和添加Fragment的過程差不多,但是需要的是replace()方法,而不是add()方法。 需要注意的是,當執行fragment事務時,比如替換或者刪除一個fragment,如果想能回退到當前,你必須在你提交fragment事務之前調用 addToBackStack()方法。

    當移除或替換fragment時將事務添加到堆棧中,被移除的Fragmeng沒有消亡,如果使用者返回,Fragment會重新啟動。如果沒有放入到堆棧中,當Fragment被替換或移除,Fragment會消亡。

       下面是替換Fragment的例子:

// Create fragment and give it an argument specifying the article it should showArticleFragment newFragment = new ArticleFragment();Bundle args = new Bundle();args.putInt(ArticleFragment.ARG_POSITION, position);newFragment.setArguments(args);FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stack so the user can navigate backtransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();

addToBackStack()方法有一個可選的字串參數,用來指定事務的唯一名稱,這個是非必須的。


參考:http://developer.android.com/training/basics/fragments/fragment-ui.html


圖二 Google IO APP


/**

* @author 張興業*  http://blog.csdn.net/xyz_lmn

* android開發進階群:241395671

*/

相關文章

聯繫我們

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