Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習之 Fragment(一):從靜態加載到動態切換

編輯:關於 Android 程式設計

Android 為什麼引入 Fragment?

如今形形色色的 Android 設備,螢幕尺寸各異。同樣的佈局,在不同設備上可能呈現出不同效果——手機上顯示完美,到了大屏平板上卻可能被拉伸得難看。因此 Android 引入了 Fragment(碎片)的概念,讓同一個 APP 能兼容不同螢幕尺寸的設備,一個 apk 就能在各式設備上完美運行。在佈局中,Fragment 實際上是 Activity 的一部分,目的是讓程式更合理、更充分地利用螢幕空間,也可以動態選擇不同的碎片來適配整個螢幕。下面就來實際體驗一下。

1. 碎片的簡單用法

首先要明白,碎片要對應一個佈局,用來確定這個碎片要放什麼、如何擺放。可以把碎片理解成裝修房子的設計圖:主螢幕是房子,我們可以劃定一塊區域專門用來放碎片(比如主臥),設計好幾種不同的裝修風格,也可以把整個房子都做成碎片。

這裡我們把一個螢幕分成兩個碎片——左碎片和右碎片。左碎片放一個 Button,右碎片放一個 TextView。

left_fragment.xml:


    

right_fragment.xml:


    
    

有了設計圖,接下來需要按圖施工。這裡要寫一個 Fragment 的子類,並重寫 onCreateView 函數——當 Activity 引用 Fragment 時會調用這個函數進行加載,我們在裡面把對應的碎片佈局加載進來。

LeftFragment.java:

public class LeftFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }
}

RightFragment.java:

public class RightFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.right_fragment, container, false);
        return view;
    }
}

Activity.xml:


    
        
            
            
        
    

這裡左邊有一個 Fragment,右邊有一個 FrameLayout,裡面放著另一個 fragment。使用 fragment 標籤添加碎片,其中的 class 屬性即為碎片的類名。

這樣就完成了碎片的靜態使用,效果如下:

2. 動態加載碎片

上面只是把碎片靜態顯示出來,還沒達到我們的目的。如何在運行時動態加載呢?比如在 Android 世界裡,想換裝修風格隨時可以換。這裡再寫一個 Another 的佈局,點一下按鈕就切換到另一個 Fragment。

another_right_fragment.xml:


    
    

同樣創建一個 AnotherRightFragment 類:

public class AnotherRightFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.another_right_fragment, container, false);
        return view;
    }
}

在主函數中實現點擊按鈕切換碎片:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button) findViewById(R.id.left_frag_button);
        b.setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
        case R.id.left_frag_button:
            // 1. 創建待添加的碎片實例
            AnotherRightFragment fragment = new AnotherRightFragment();
            // 2. 獲取 FragmentManager
            FragmentManager fragmentManager = getFragmentManager();
            // 3. 開啟一個事務
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            // 4. 向容器內添加碎片,使用 replace() 傳入容器 id 和碎片實例
            transaction.replace(R.id.right_layout, fragment);
            // 5. 提交事務
            transaction.commit();
            default:
                break;
        }
    }
}

這裡通過 FragmentManager 開啟一個事務,利用事務完成碎片的 replace。事務本是資料庫名詞,日後可再深入了解,此處先記住即可。點擊按鈕後的效果圖如下:

3. 在碎片中模擬返回棧

從上面的動態加載中可以看到,按返回鍵時直接退出了,並沒有 Activity 棧那樣的感覺。能否實現按返回鍵時回到上一個 fragment 呢?其實很容易,一個 API 就能搞定,就是 FragmentTransaction 中的 addToBackStack 方法:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button) findViewById(R.id.left_frag_button);
        b.setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
        case R.id.left_frag_button:
            AnotherRightFragment another = new AnotherRightFragment();
            FragmentManager manager = getFragmentManager();
            FragmentTransaction trans = manager.beginTransaction();
            trans.replace(R.id.right_layout, another);
            trans.addToBackStack(null);
            trans.commit();
            break;
        default:
            break;
        }
    }
}

4. 動態加載佈局的技巧

這個功能的實質,就是我們設計兩套方案讓系統自行選擇:設計一個單頁 layout、一個雙頁 layout,使用大屏平板時自動選擇雙頁顯示,使用手機時則選擇單頁顯示。要完成這個功能就需要用到限定符——它其實就是一道界線,用來劃分螢幕大小、解析度等。

這裡根據螢幕大小的特徵限定符,新建一個 large 的 layout,方法如下圖:

新建之後,activity_main 中會出現兩個 xml 檔案,其中一個後面帶有 large 標示,代表它提供給超大螢幕設備使用。兩個檔案的內容如下。

activity_main.xml:


    
    

activity_main.xml(large):


    
    
    

分別在手機和平板上運行看看效果。手機加載普通 xml:

平板加載 large 的 xml:

總結

以上主要介紹了 Fragment 的靜態使用、動態加載,以及如何適配不同設備。下一篇將專門介紹碎片的生命週期,以及碎片與 Activity 之間的通訊,並附一個小實例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved