Android中使用全局变量有两种方法:
一种是自定义一个类继承Application;另一种是定义一个类,将里面的方法和变量全部设置成静态。
首先讲第一种:
1.这个很简单,只需要你将全局变量放到该类中作为成员变量即可,最好设置成private,然后通过方法对其进行设置和提取。注意的是:该类是无法访问到其它类中的变量。
2.在Manifests.xml中的中添加一个android:name=”你定义的类的路径名”
例如:
3.引用该类,这里我定义的是MyApp类:MyApp myApp = (MyApp) getApplication();
具体代码:
MyApp.class
public class MyApp extends Application{
public String str_public;
private String str_private;
public void setStr_private(String str){
str_private = str;
}
public String getStr_private(){
return str_private;
}
}
MainActivity.class
MyApp myApp = (MyApp)getApplication();
String str = "this is Main of Private";
myApp.setStr_private(str);
TextView textview = (TextView)findViewById(R.id.text1_private);
textview.setText(myApp.getStr_private() );
myApp.str_public = "this is Main of Public";
TextView textView2 = (TextView)findViewById(R.id.text1_public);
textView2.setText(myApp.str_public );
Inflate.class
MyApp myApp = (MyApp)getApplication();
String str = "this is Inflate of Private";
myApp.setStr_private(str);
TextView textview = (TextView)findViewById(R.id.text2_private);
textview.setText(myApp.getStr_private());
myApp.str_public = "this is Inflate of Public";
TextView textView2 = (TextView)findViewById(R.id.text2_public);
textView2.setText(myApp.str_public );
效果:
第二种:
定义一个public的类,将里面的变量设为static,那么每当你使用该类时,里面的变量不会重新初始化,而是保留上次使用时所保存的值。
代码如下:
Data.class
public class Data {
private static String str;
public static String getStr(){
return str;
}
public static void setStr(String string){
str = string;
}
}
MainActivity.class
Data data = new Data();
data.setStr("This is in Main");
TextView textview = (TextView)findViewById(R.id.text1_public);
textview.setText(data.getStr() );
Inflate.class
Data data = new Data();
data.setStr("This is in Inflate");
TextView textview = (TextView)findViewById(R.id.text2_public);
textview.setText(data.getStr() );
效果: