《第一行代码》读书笔记:第十三章/进阶技巧(未完)
来源:互联网 发布:2016广电禁止网络电视 编辑:程序博客网 时间:2024/05/27 00:50
1:全局获取Context。
Android中有一个Application类,程序启动时它会初始化。我们通过定制自己的Application来管理一些全局的状态信息,如Context。
public class MyApplication extends Application{//全局获取Contextprivate static Context context;@Overridepublic void onCreate() {// TODO Auto-generated method stubcontext=getApplicationContext();}public static Context getContext(){return context;}}getApplicationContext()获得程序级别的context;
getContext()返回context值。
不过需要告知系统初始化MyApplication而不是默认的Application,在Manifest中修改<application>:
<application android:name="com.包名.MyApplication">
2:Intent传递对象
1)putExtra()
有时候我们需要在Intent中添加一些附加数据以达到传值效果。
比如添加如下代码从FirstActivity到SecondActicity:
在FirstActivity中
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);intent.putExtra("string_data","hello");intent.putExtra("int_data",100);startActivity(intent);而在SecondActivity中接收的话:
getIntent().getStringExtra("string_data");getIntent().getIntExtra("int_data",0);
putExtra()支持的数据类型有限,有时我们要传递一些自定义对象。这时候就要用到传递对象的技巧。
Serializable,序列化,原理是将一个对象转换成可存储或可运输的状态,序列化后的对象就可以在网络上进行传输。
将对象所在的类实现Serializable接口就相当于序列化了对象,然后就直接putExtra("标记",对象),接收时则用getSerializableExtra();
Parcelable的原理是将一个对象分解成Intent支持的数据类型,同样需要实现Parcelable接口,然后重写describeContents()和writeToParcel()方法,前者return 0就行,后者需要writeString(),writeInt()之类将Person类中的字段一一写出。除此之外还要提供一个CREATOR常量,重写两个方法。其中readString()之类方法必须与之前write时顺序一致。
实例:
public class Person implements Parcelable{private String name;private int age;@Overridepublic int describeContents(){return 0;}@Overridepublic void writeToParcel(Parcel dest,int flags){dest.writeString(name);dest.writeInt(age);}public static final Parcelable.Creater<Person> CREATOR=new Parcelable.Creater<Person>(){ @Override public Person createFromParcel(Parcel source){ person.name=source.readString(); person.age=source.readInt(); return person;}@Overridepublic Person[] newArray(int size){return new Person[size];}};//接收使用如下方法Person person=(Person)getIntent().getParcelableExtra("标记");
0 0
- 《第一行代码》读书笔记:第十三章/进阶技巧(未完)
- 《第一行代码》读书笔记 (第十章至第十三章)
- 第一行代码,第十三章-----高级技巧
- 《第一行代码》读书笔记(十二)----高级技巧
- 第一行代码 读书笔记 第1章
- 第一行代码 读书笔记 第2章
- 读书笔记 《第一行代码》 第13章
- 《第一行代码》读书笔记
- 第一行代码读书笔记
- 《第一行代码》读书笔记
- 《第一行代码》读书笔记(第三章,第四章)
- 《第一行代码》读书笔记(第五章,第六章)
- 《第一行代码》读书笔记(第一章,第二章)
- 第一行代码读书笔记___1-2章
- 第一行代码读书笔记___3章
- 第一行代码读书笔记___4章
- 第一行代码Android第二章读书笔记
- 第一行代码(第二版)读书笔记
- Windows热键注册(反汇编方法 查看win32api 原理)
- 2016搜狗公司研发工程师笔试题
- 第八周项目3——顺序串算法(4)
- 第七周项目5--排队看病模拟
- 第九周上机实践项目1—— 猴子选大王(数组版)
- 《第一行代码》读书笔记:第十三章/进阶技巧(未完)
- HAOI2006 受欢迎的牛
- 第八周 项目3-顺序串算法(4)
- 第7周SHH数据结构—【项目2 - 建立链队算法库】
- C++调用Python代码
- 第9周项目1——猴子选大王(数组版)
- 第八周项目2-建立链串的算法库
- (unity)用SQLite Manager工具写好的数据库sqlite文件如何随着发布导入安卓手机
- android 广告轮播小圆点封装