android 如何定义全局变量

 我来答
☆你大爷☆hdaw
推荐于2016-10-12 · TA获得超过131个赞
知道答主
回答量:122
采纳率:0%
帮助的人:59.1万
展开全部
找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。 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。 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): --方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是 android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。
双四别阴我
2015-07-01 · TA获得超过2282个赞
知道大有可为答主
回答量:1250
采纳率:57%
帮助的人:1152万
展开全部
你可以在任意一个.java文件中定义全局变量,定义成
public static final 的就可以了,比如可以在MyApplication中定义:
public static final boolean DEBUG = false;
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
大鹏蔡
2015-07-23 · TA获得超过1769个赞
知道小有建树答主
回答量:1117
采纳率:80%
帮助的人:424万
展开全部
1、新建一个类
2、在类里面建一些 public static final 的变量
3、在需要调用的地方,类名.变量名,即可调用
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
baikewsp
推荐于2018-05-07 · TA获得超过1万个赞
知道小有建树答主
回答量:4588
采纳率:42%
帮助的人:653万
展开全部
可以直接建一个类GlobalInfo
public static String name;
调用:GlobalInfo.name

官方建议自己建一个类继承Application
使用方法参考http://blog.csdn.net/feiyangxiaomi/article/details/9966215
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2013-10-25
展开全部
你搜一下android Application就知道了
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
收起 更多回答(3)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式