安卓笔记20170112

一,全局获取Context的技巧


       借助Application类,每当应用程序启动的时候,系统就会自动将这个类进行初始化。

       public class MyApplication extends Application{
            private static Context context;

            public void onCreate(){
                 context = getApplicationContext();
            }

            public static Context getContext(){
                 return context;
            }
       }

       最后在配置文件的<application>标签下进行指定

       <application

                application:name="com.example.xxxx.MyApplication"

                 ...

                 ...>

       </application>

二,使用Intent传递对象

      1.Serializable方式

      

public class Person implements Serializable {
	
	private String name;
	
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

       在发送方活动里的代码如下

Person person = new Person();
		 person.setName("Tom");
		 person.setAge(20);
		 Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
		 intent.putExtra("person_data", person);
		 startActivity(intent);

       在接收方活动里代码如下

Person person = (Person) getIntent().getSerializableExtra("person_data");


       2.Parcelable方式

         Serializable是将对象进行序列化, Parcelable方式的实现原理是将一个完整的对象进行分解,分解后的每一部分都是Intent所支持的数据类型


public class Person implements Parcelable {

	private String name;
	
	private int age;
	
	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
	}
	
	public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>(){

		@Override
		public Person createFromParcel(Parcel source) {
			Person person = new Person();
			person.name = source.readString();
			person.age = source.readInt();
			return person;
		}

		@Override
		public Person[] newArray(int size) {
			return new Person[size];
		}
	};
}


         发送方活动里的传递代码是一样的,接收方活动代码如下

Person person = (Person) getIntent().getParcelableExtra("person_data");




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值