关于android中是否可以使用全局变量,当然可以。做Java的人肯定都用过全局变量了
,使用方法无非是定义一个静态变量,public类型,这样在其他类中就可以直接调用了,
android中也可以这样使用。但是,android中这样使用全局变量是不是最符合android的架构呢
在国外的论坛里找到了下面的解决办法:
The more general problem you are encountering is how to save stateacross several Activities
and all parts of your application. A staticvariable (for instance, a singleton) is
a common Java way of achievingthis. I have found however, that a more elegant way in
Android is toassociate your state with the Application context.

--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。</strong><br />

As you know, each Activity is also a Context,
which is informationabout its execution environment in the broadest sense.
Your applicationalso has a context, and Android guarantees
that it will exist as asingle instance across your application
--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。

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 andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):<br />
--方法是创建一个属于你自己的android.app.Application的子类,
然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,
你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,
进而获取其中的状态(变量)。
请看如下demo
public class MyApplication extends Application{
private int num;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setNum(10);
}
public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

}
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final String TAG="---------MainActivity--------";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyApplication myApp=(MyApplication)getApplication();
Log.i(TAG,String.valueOf(myApp.getNum()));
}
}
在AndroidMenifest.xml配置如下:
....
<application android:name=".MyApplication" android:icon="@drawable/icon" android:label="@string/app_name">
.....
这样即可实现全局变量。

更多相关文章

  1. Android开发人员的10大抱怨
  2. Android小项目合集(经典教程)包含十五个Android开发应用实例
  3. Android(安卓)打造编译时注解解析框架 这只是一个开始
  4. android selector 背景选择器的使用, button (未点击,点击,选中保持
  5. Android(安卓)Trick 7: 把TextView中的文字添加阴影效果及Style
  6. Android下SQLite数据库编程学习系列之二---在Android下使用SQLit
  7. Android(安卓)Trick 7: 把TextView中的文字添加阴影效果及Style
  8. android ndk 开发之 在 应用程序中使用 jni
  9. 使用Eclipse搭建Android的开发环境

随机推荐

  1. android 模拟按键
  2. Android菜单实现两种方式
  3. [Android]Bluetooth Smart Android(安卓)
  4. android视频截图
  5. android 多媒体扫描过程(Android(安卓)Med
  6. android表格数据移动功能
  7. Android(安卓)Spinner
  8. android之MultiAutoCompleteTextView
  9. Android——Hardware Acceleration
  10. Android(安卓)通知Notification的两种实