Android 使用全局变量
AI摘要
本文介绍了在Android开发中使用全局变量的两种方法:1. 使用静态类,通过声明一个静态变量,可以直接通过类名.变量名进行访问;2. 使用Application类,通过创建一个继承自Application的子类,并在其中定义全局变量和相应的get/set方法,然后在其他类中通过获取Application实例来访问这些全局变量。文章建议使用第二种方法,因为它更符合Android的开发理念,且更安全。
1、使用静态类:
package com.Declare;
public class Declare{
public static String UserName="";
}
调用就不再过写了,直接使用类名.变量名就可以调用!
2、使用Application
代码
package com.Declare;
import android.app.Application;
public class Declare extends Application {
private String strAccounts = ""; // 操作帐号
public void setAccounts(String accountsNO) {
this.strAccounts = accountsNO;
}
public String getAccounts() {
return this.strAccounts;
} // 操作密码
public void setAccountsPassWord(String passWord) {
this.strAccountsPWD = passWord; }
public String getAccountsPassWord() {
return this.strAccountsPWD;
}
}
在类中调用的话是这样子调用的!
Declare declare = (Declare) getApplicationContext();
declare.getAccounts();
declare.setAccounts("");
要能成功调用,必须要声明Application的子类: android:name="com.Declare.Declare"
而且按照Java及C#的种编辑思想的话,还是建议使用第二种试,这样对于系统的安全是好的!这样也是符合Android这种思想的,因此建议使用第二种方式,设置公共变量!
读者留言 0 条
一纸留言,便是山水间的一次相逢。
还没有留言,欢迎写下第一段交流。