Android中全局变量的定义

 

当我们需要在整个应用程序中定义全局变量时,可通过扩展 Android 的 Application 类来实现,这里是一个基础的类用来操作全局的应用状态。

下面是创建全局变量的步骤:

1) 创建一个新类扩展自 Application 类:(这里务必写在一个单独的.java文件,免得出现些奇怪的崩溃错误)

   
   
  1. public  class  Global extends Application { 
  2.     private Boolean _notification=false
  3.     public Boolean get_notification() { 
  4.         return _notification; 
  5.     } 
  6.     public void set_notification(Boolean _notification) { 
  7.         this._notification = _notification; 
  8.     } 

2) 添加新类到 AndroidManifest 文件作为 application 标签的属性:(看清楚是属性在内标签的)

   
   
  1. <application 
  2. android:name=".Global" 
  3.         .... /> 

3) 你可通过 Context.getApplicationContext() 方法来访问到该全局变量:(最后这不就没有什么问题了)

   
   
  1. Global global; 
  2.     public void onCreate(Bundle savedInstanceState) { 
  3.         global=((Global)getApplicationContext()); 
  4.         Boolean notification=global.get_notification();} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 定义全局变量有以下几种方法: 1. 在 Application 类定义全局变量 可以在自定义的 Application 类定义全局变量,这样在整个应用程序都可以访问到该变量。具体的实现步骤如下: - 创建一个继承自 Application 类的自定义类; - 在自定义定义一个静态变量; - 在 AndroidManifest.xml 文件指定自定义类。 示例代码如下: ``` public class MyApplication extends Application { public static int globalVar = 0; } ``` 可以在任何地方通过 `MyApplication.globalVar` 来访问该全局变量。 2. 使用 SharedPreferences 存储全局变量 SharedPreferences 是一种轻量级的数据存储方式,可以用来存储一些简单的全局变量。具体的实现步骤如下: - 获取 SharedPreferences 对象; - 使用 SharedPreferences.Editor 对象保存全局变量; - 在需要访问全局变量的地方获取 SharedPreferences 对象,并通过 key 值获取全局变量。 示例代码如下: ``` public class MyApplication extends Application { private SharedPreferences sharedPreferences; @Override public void onCreate() { super.onCreate(); sharedPreferences = getSharedPreferences("globalVar", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("var1", 0); editor.apply(); } public int getGlobalVar() { return sharedPreferences.getInt("var1", 0); } public void setGlobalVar(int var) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("var1", var); editor.apply(); } } ``` 可以在任何地方通过 `MyApplication.getInstance().getGlobalVar()` 和 `MyApplication.getInstance().setGlobalVar(var)` 来访问和修改该全局变量

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值