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

Android 動態建立 Fragment 的實作

編輯:關於 Android 程式設計

上一篇我們介紹了靜態建立 Fragment 的方式,但這在實際開發中幾乎不會用到,絕大多數情況都是採用動態建立。所謂動態建立,就是依據某個條件在執行期即時產生 Fragment。本文以依螢幕方向切換不同 Fragment 為例進行示範。

首先建立一個名為 dynamicFragment 的 Android 專案。

MainActivity.java

package com.example.dynamicfragment;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.WindowManager;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WindowManager wm = getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        // 1. 取得 fragment 的管理器
        FragmentManager fm = getFragmentManager();
        // 2. 開啟事務,保證界面更新要嘛同時成功、要嘛同時失敗
        FragmentTransaction ft = fm.beginTransaction();
        if (height > width) {
            // 直屏,android.R.id.content 代表當前應用的 activity
            ft.replace(android.R.id.content, new Fragment1());
        } else {
            // 橫屏
            ft.replace(android.R.id.content, new Fragment2());
        }
        ft.commit();
    }
}

Fragment1.java

package com.example.dynamicfragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, null);
    }
}

Fragment2.java

package com.example.dynamicfragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, null);
    }
}

XML 版面檔這裡就不再貼上,內容只是一個 TextView,沒有太多可說的。整體邏輯是:當螢幕為橫屏時顯示 Fragment1,為直屏時顯示 Fragment2。

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