zoukankan      html  css  js  c++  java
  • 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):

      

    Java代码  收藏代码
    1. class MyApp extends Application {  
    2.   
    3.   private String myState;  
    4.   
    5.   public String getState(){  
    6.     return myState;  
    7.   }  
    8.   public void setState(String s){  
    9.     myState = s;  
    10.   }  
    11. }  
    12.   
    13. class Blah extends Activity {  
    14.   
    15.   @Override  
    16.   public void onCreate(Bundle b){  
    17.     ...  
    18.     MyApp appState = ((MyApp)getApplicationContext());  
    19.     String state = appState.getState();  
    20.     ...  
    21.   }  
    22. }  

    This has essentially the same effect as using a static variable or singleton,

    but integrates quite well into the existing Android framework.

    Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).

    然后再manifest中添加应用:

    Xml代码  收藏代码
    1. <application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">  
    2.         <activity android:name=".ClickableListItemActivity"  
    3.                   android:label="@string/app_name">  
    4.             <intent-filter>  
    5.                 <action android:name="android.intent.action.MAIN" />  
    6.                 <category android:name="android.intent.category.LAUNCHER" />  
    7.             </intent-filter>  
    8.         </activity>  
    9.   
    10.     </application>  

      

    说明:

    1. 需添加的内容:android:name=".your_App_Name"

    2. 位置:当前activity所在的位置,(我刚开始以为需要新建一个<application></application>)

  • 相关阅读:
    将多个字典添加到数组输出
    获取字典中的数组
    数组内的元素排序
    1字符串中的world替换为i bookan wisdom2.字符串的相加字符串输出,长度3比较字符串大小4截取字符串5字符串内所有a都替换成A6判断字符串是否以http开头7将字符串内admin和123截取出来8字符添加
    判断是否有前缀后缀
    截取字符串
    大小写
    数据存字典,block排序,删除
    block排序
    描述器 排序(根据属性)
  • 原文地址:https://www.cnblogs.com/xiaochao1234/p/4091952.html
Copyright © 2011-2022 走看看