Java 创建全局变量

1.新建一个类随便取个名叫GlobalData.java好了

2.编写类

public class GlobalData extends Application{//要继承Application
    private boolean a;
    private String b;

    
    public boolean geta(){//a数据的get方法
        return this.a;
    }
    public void seta(boolean a){//a数据的set方法
        this.a= a;
    }

    public String getb(){//b数据的get方法
        return this.b;
    }
    public void setb(String b){//b数据的set方法

        this.b= b;
    }
   
  public void onCreate(){
        super.onCreate();
        a = false;初始化
        b = "";//初始化
    }

​​​​​​​}

3.在AndroidManifest.xml

里修改

    <application
        android:allowBackup="xxx"
        android:label="xxx"
        android:roundIcon="xxx"
        android:supportsRtl="xxx"
        android:theme="xxx"
        android:icon="xxx"
        android:name=".GlobalData"//这里添加
        >

4.使用

在需要用到的函数里添加

final GlobalData app = (GlobalData)getApplication();

app.seta(true);
xxx = app.geta();
app.setb("设置b");
String xxx = app.getb();

猜你喜欢

转载自blog.csdn.net/weixin_41012767/article/details/112348036