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

Android 中使用 Application 保存全域變數

編輯:關於 Android 程式設計

在開發中經常需要跨頁面共享資料,Android 提供了幾種保存全域變數的方式。

1、透過一個 Data.java 實例類,可以實現全域資料保存,這部分學過 Java 的都了解,此處不再贅述。

2、Android 特有的 Application 類是應用的入口,其生命週期貫穿整個 App 運行過程,非常適合在裡面定義全域變數。

public class baseApplication extends Application {
    private float screenWidth;
    private float screenHeight;
    public float getScreenWidth() {
        return screenWidth;
    }
    public void setScreenWidth(float screenWidth) {
        this.screenWidth = screenWidth;
    }
    public float getScreenHeight() {
        return screenHeight;
    }
    public void setScreenHeight(float screenHeight) {
        this.screenHeight = screenHeight;
    }
}

使用時直接透過 getApplicationContext() 取得 Application 物件再呼叫 getter 即可:

baseApplication b = (baseApplication) getApplicationContext();
float width = b.getScreenWidth();
float height = b.getScreenHeight();

別忘了要在 AndroidManifest.xml 的 <application> 標籤上用 android:name 指定這個自訂的 Application 類,它才會生效。

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