开发学院手机开发Android 开发 Android中Activity共享变量的另一方法:Applicati... 阅读

Android中Activity共享变量的另一方法:Application context

 2010-05-14 16:56:00 来源:WEB开发网 闂傚倸鍊风欢姘缚瑜嶈灋闁圭虎鍠栫粻顖炴煥閻曞倹瀚�闂傚倸鍊风粈渚€骞夐敓鐘插瀭闁汇垹鐏氬畷鏌ユ煙閹殿喖顣奸柛搴$У閵囧嫰骞掗幋婵冨亾閻㈢ǹ纾婚柟鐐灱濡插牊绻涢崱妤冃℃繛宀婁簽缁辨捇宕掑鎵佹瀸闂佺懓鍤栭幏锟�濠电姷鏁告慨顓㈠箯閸愵喖宸濇い鎾寸箘閹规洟姊绘笟鈧ḿ褍煤閵堝悿娲Ω閳轰胶鍔﹀銈嗗笂閼冲爼鍩婇弴銏$厪闁搞儮鏅涙禒褏绱掓潏鈺佷槐闁轰焦鎹囬弫鎾绘晸閿燂拷闂傚倸鍊风欢姘缚瑜嶈灋闁圭虎鍠栫粻顖炴煥閻曞倹瀚�  闂傚倸鍊烽懗鑸电仚缂備胶绮〃鍛村煝瀹ュ鍗抽柕蹇曞У閻庮剟姊虹紒妯哄闁诲繑姘ㄩ埀顒佸嚬閸撶喎顫忓ú顏勫瀭妞ゆ洖鎳庨崜浼存⒑闁偛鑻晶顔剧磼婢跺﹦绉虹€殿喖顭锋俊姝岊槷闁稿鎹囧Λ鍐ㄢ槈濞嗗繑娈橀梻浣风串缂嶁偓濞存粠鍓熼崺鈧い鎺戝€归弳顒勬煕鐎n亷韬€规洑鍗冲鍊燁槾闁哄棴绠撻弻銊╂偆閸屾稑顏�
核心提示:Android中在不同Activity中传递变量,通常使用Intent中Bundle添加变量的操作方法,Android中Activity共享变量的另一方法:Application context,view plaincopy to clipboardprint?Intent intent = new Intent();

Android中在不同Activity中传递变量,通常使用Intent中Bundle添加变量的操作方法。

view plaincopy to clipboardprint?

Intent intent = new Intent();

intent.setClass(A.this, B.class);

Bundle bundle = new Bundle();

bundle.putString("Info", "Information");

intent.putExtras(bundle);

startActivity(intent);

Intent

intent = new Intent();

intent.setClass(A.this, B.class);

Bundle bundle = new Bundle();

bundle.putString("Info", "Information");

intent.putExtras(bundle);

startActivity(intent);

不过在多个Activity中经常使用同一变量时,使用Bundle则比较麻烦,每次调用Activity都需要设置一次。

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

新建一个类,继承自Application

view plaincopy to clipboardprint?

class MyApp extends Application {

private String myState;

public String getState() {

return myState;

}

public void setState(String s) {

myState = s;

}

}

class MyApp extends

Application {

private String myState;

public String getState() {

return myState;

}

public void setState(String s) {

myState = s;

}

}

在AndroidManifest.xml的application加个name属性就可以了,如下面所示:

view plaincopy to clipboardprint?

< p>

android:name=".MyApp" android:icon="@drawable/icon"

android:label="@string/app_name">

使用时:

view plaincopy to clipboardprint?

class Blah extends Activity {

1 2  下一页

Tags:Android Activity 共享

编辑录入:coldstar [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
更多精彩
    赞助商链接

    热点阅读
      焦点图片
        最新推荐
          精彩阅读