我想在android中的活動之間傳遞一個或多個變量。一種解決方案是使用全局變量,它是在這裏解釋: Android global variable 我在這裏重複:Android在活動之間傳遞變量
可以擴展基android.app.Application類並添加成員變量,像這樣:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
然後在你的活動,你可以獲取和設置變量,像這樣:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
我想要使用它並在按下ListView上的某個項目時在其中一個活動中設置全局變量。所以我有這樣的代碼:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
.
.
.
((MyApplication) this.getApplication()).setSomeVariable("foo");
}
});
但是我得到它說的錯誤「的方法getApplication()是未定義的類型新AdapterView.OnItemClickListener(){}」。
我想知道我得到這個錯誤的原因是什麼,以及如何解決這個錯誤,或者將一個變量從一個活動傳遞給另一個的更好方法。
感謝,
TJ
MyApplication是與我想要使用setSomeVariable()的地方不同的類。可以說我希望在MyOtherApplication中完成它,而setSomeVariable方法在MyApplication中定義。所以你所建議的不是現在的樣子。 – TJ1
對於我寫的代碼,「getApplication()」方法可以獲得所需的類,當您在MyOtherApplication類中您必須編寫MyOtherApplication.this ...因爲您在匿名類中調用它並且關鍵字「this」指向內部類。 – Michele