android的全局变量

关于android中是否可以使用全局变量,当然可以。做Java的人肯定都用过全局变量了,使用方法无非是定义一个静态变量,public类型,这样在其他类中就可以直接调用了,android中也可以这样使用。

 

As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.

The way to do this is to create your own subclass of android.app.Application , and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):

 

 

 


 

public class MyApp extends Application {
    private String myState;

    public String getState() {
        return myState;
    }
   
    public void setState(String state){
        myState = state;
    }
}

 

class Blah extends Activity { 
  
  @Override 
  public void onCreate(Bundle b){ 
    ... 
    MyApp appState = ((MyApp)getApplicationContext()); 
    String state = appState.getState(); 
    ... 
  }

 

然后再manifest中添加属性application android:name=".MyApp",如下

 

<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name"> 
<activity android:name=".ClickableListItemActivity" 
    android:label="@string/app_name"> 
        <intent-filter> 
            <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER" /> 
        </intent-filter> 
</activity> 
   
</application>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值