android使用全局变量的方法
来源:互联网 发布:linux查看网络状态命令 编辑:程序博客网 时间:2024/05/29 08:45
使用application来保存全局变量
1定义Data类继承Application Data.class
import android.app.Application;public class Data extends Application{private String b;public String getB(){return this.b;}public void setB(String c){this.b= c;}@Overridepublic void onCreate(){b = "hello";super.onCreate();}}2在manifest.xml中声明application
android:name="com.animator1.Data" >
3创建两个Activity
MainActivity.class
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Button btn = (Button) this.findViewById(R.id.button1);final TextView txtview = (TextView) this.findViewById(R.id.main);final Data app = (Data)getApplication();txtview.setText(app.getB());btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubapp.setB("no_hello");txtview.setText(app.getB());Intent intent = new Intent(MainActivity.this, secondActivity.class);startActivity(intent);}});}}
secondActivity.class
public class secondActivity extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.second);Button btn = (Button) this.findViewById(R.id.button2);final TextView txtview = (TextView) this.findViewById(R.id.second);final Data app = (Data)getApplication();txtview.setText(app.getB());btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubapp.setB("hello");txtview.setText(app.getB());Intent intent = new Intent(secondActivity.this, MainActivity.class);startActivity(intent);}});}}
说明:程序首先进入MainActivity.class中,获取Data中变量b的值,显示图1所示的界面hello,单击button后app.setB("no_hello"), 修改变量b的值。
跳转到secondActivity.class,获取Data中变量b的值,显示图2所示的界面no_hello,单击button后app.setB("hello"), 修改变量b的值。
跳转回MainActivity.class…… 循环
0 0
- android使用全局变量的方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- Android 全局变量的使用
- android 全局变量的使用
- QT 使用全局变量的方法
- <Android>Application全局变量的使用
- android 关于全局变量的使用
- Android中全局变量的实现方法
- Android中全局变量的实现方法
- c++多文件使用全局变量的方法
- 自制爬虫搜索种子和电影
- 防反接保护电路 设计
- [leetcode]Remove Linked List Elements
- tomcat快速部署运行
- Android的GridView控件点击图片变暗效果
- android使用全局变量的方法
- C# 中的委托和事件
- detection/region/object proposal 方法综述文章
- Dynamic Web project转成Maven项目
- C语言知识概述
- 我们说的oc是动态运行时语言是什么意思?
- BoneCP学习笔记——配置参数
- OgreTerrain 实现原理分析
- 【深入理解Cocos2d-x 3.x】 如何进行合理的内存分配