[Android]android Global variable 寫法
寫了一陣子android,最常遇到的問題就是多個Activity 中需要傳送資料與共用管理資料,解決方法可以用Bundle的寫法去處理,但我發現使用Application去產生Global variable(全域變數)這個方法方便許多,也比較不會把資料錯亂,因此今天來分享使用Application 的方法,共同使用全域變數.
首先需要先創立的一個class來繼承Application
import android.app.Application;
public class GlobalVariable extends Application {
private String Word; //要傳送的字串
//修改 變數字串
public void setWord(String word){
this.Word = word;
}
//顯示 變數字串
public String getWord() {
return Word;
}
}
並在AndroidMainifest.xml新增android:name,並填上剛剛創建的class名稱,強調名稱前一定要記得加 ,本人就是一不小心忘記加結果跑一堆bug.
<application
android:name=".GlobalVariable"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
以上都設定完成,只要在你要使用這全域變數的地方加入一下內容就可以使用了
GlobalVariable User = (GlobalVariable)getApplicationContext();
User.setWord("Go to Next");
String Word=User.getWord();
這種方法是不是很方便壓,這樣可以使程式更加簡潔,再傳輸資料上也非常快速,希望大家也能學習到這個方法唷
如果想要知道更詳細的寫法可以參考以下網址,有更詳細的內容:
