安卓笔记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");




©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页