传递数据包Bundle基础上
在com.m.sendargs中添加一个java class为User

package com.m.sendargs;

/**
 * Created by Z on 2015/10/18.
 */
public class User {
    private String name;
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age){
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public User(String name,int age){
        this.name=name;
        this.age=age;
    }

}

在MainActivity.java中添加

 Intent i=new Intent(MainActivity.this,TheAty.class);
//                i.putExtra("data","你好,这是activity之间参数的传递");
//                Bundle b=new Bundle();
//                b.putString("name","这是Bunle传递数据包");
//                b.putInt("age",2);
//                b.putString("name1","这是存在的name1");
//                i.putExtras(b);
//                i.putExtra("data",b);
                i.putExtra("user",new User("这是传递对象",2));//此处就报错

报错中有Serializable和Parcelable
Serializable是java语言内置序列化对象接口
Parcelable是安卓平台语言用于序列化对象接口
先处理Serializable
在User.java中改为
public class User implements Serializable{
在TheAty.java中

 Intent i= getIntent();
//        Bundle data=i.getExtras();
//        Bundle data=i.getBundleExtra("data");
        tv= (TextView) findViewById(R.id.tv);
//        tv.setText(i.getStringExtra("data"));
//        tv.setText(String.format("name=%s,age=%d,name1=%s",data.getString("name"),data.getInt("age"),data.getString("name1", "这是name1不存在时的默认值")));
        User user= (User) i.getSerializableExtra("user");
        tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge()));

运行
再处理Parcelable
在User.java中改为public class User implements Parcelable{
此时有报错选择Implement Methods即

@Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(getName());
        dest.writeInt(getAge());

    }
    public static final Creator<User> CREATOR=new Creator<User>() {
        @Override
        public User createFromParcel(Parcel source) {
            return new User(source.readString(),source.readInt());
        }

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

在TheAty.java中

//        User user= (User) i.getSerializableExtra("user");
        User user=i.getParcelableExtra("user");

因为在MainActivity.java中i.putExtra("user",new User("这是传递对象",2));中User.java中实现了全自动重载到android.os.Parcelable函数

标签:安卓开发

你的评论