android使用全域性變數

weixin_34304013發表於2011-12-29
一開始我是用static來做全域性,後來在網上看見老外有一個很好的辦法 
public class MyApp extends Application { 
private Integer[] state; 
public Integer[] getState() { 
return state; 
public void setState(Integer[] state) { 
this.state = state; 
@Override 
public void onCreate() { 
// TODO Auto-generated method stub 
super.onCreate(); 
setState(we); 
}//一定要在onCreate方法裡給變數賦值 
public Integer[] we=new Integer[]{ 
    R.drawable.b_0,R.drawable.b_1,R.drawable.b_2, 
    R.drawable.b_3,R.drawable.b_4,R.drawable.b_5 
}; 
在所需要的activity中使用 
MyApp appState = (MyApp)getApplicationContext(); 
Integer[] we = appState.getState(); 
來獲取,最後一步別忘了在manifest中的application標籤中新增 android:name=".MyApp"(這兒不是新建<application></application>)

相關文章