每日总结2023-04-27——关于全局变量的基础使用

JJTyyds / 2023-04-27 / 原文

今天完成了对全局变量的使用

package com.example.math;
/*
* 全局变量
* */
import android.app.Application;

public class CustomApplication extends Application {
    private static final String VALUE = "111";

    private String value;

    @Override
    public void onCreate()
    {
        super.onCreate();
        setValue(VALUE); // 初始化全局变量
    }

    public void setValue(String value)
    {
        this.value = value;
    }

    public String getValue()
    {
        return value;
    }
}

在声明中加上

  android:name=".CustomApplication"

使用:

 user_name = findViewById(R.id.userName);
        user_password = findViewById(R.id.userPassword);
        String userName = user_name.getText().toString();
        CustomApplication app = (CustomApplication) getApplication();
        app.setValue(userName);//setValue调用设置变量

 

TextView tv_name = findViewById(R.id.mel_tv_2);
        CustomApplication app = (CustomApplication) getApplication();
        String name = app.getValue();
        tv_name.setText(name);  //getVlue获取变量