码迷,mamicode.com
首页 > 其他好文 > 详细

Intent使用Parcelable传递对象

时间:2016-05-20 13:17:14      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

package com.pingyijinren.test;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;

/**
 * Created by Administrator on 2016/5/20 0020.
 */
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];
        }
    };

    public void setName(String name){
        this.name=name;
    }

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

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }
}
package com.pingyijinren.test;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class IndexActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        Intent intent=new Intent(this,TransferObjectActivity.class);
        Person person=new Person();
        person.setAge(26);
        person.setName("张钦雄");
        intent.putExtra("person",person);
        startActivity(intent);
    }
}
package com.pingyijinren.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class TransferObjectActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_object);

        Person person=getIntent().getParcelableExtra("person");
        Log.d("MainActivity",person.getName()+" "+person.getAge());
    }
}

 

Intent使用Parcelable传递对象

标签:

原文地址:http://www.cnblogs.com/zqxLonely/p/5511613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!