前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android Parcelable

Android Parcelable

作者头像
阳光岛主
发布2019-02-19 18:16:39
5920
发布2019-02-19 18:16:39
举报
文章被收录于专栏:米扑专栏米扑专栏

Parcelable(SDK)

Interface for classes whose instances can be written to and restored from a Parcel

Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creatorinterface.

Passing data between activities is quite easy. 

You would normally do that using the Bundle packed into an intent. But sometimes you need to pass complex objects from one activity to another. 

One workaround would be to keep a static instance of the object int your Activity and access it from you new Activity. This might help, but it's definitely not a good way to do this. 

To pass such objects directly through the Bundle, your class would need to implement the Parcelable interface. 

Example:

MainActivity, SubActivity, Person

MainActivity

代码语言:javascript
复制
package com.learn;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

	private static final String TAG = "Parcelable";
	
	public static final String KEY = "key";
	private Button btn;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.d(TAG, "MainActivity");
        
        btn = (Button)findViewById(R.id.btn);
    	btn.setOnClickListener(this);
    	
    }
    
    
    @Override
    public void onClick(View v) {

        Log.d(TAG, "onClick");
        
    	if(R.id.btn == v.getId()){
    		
    		Person mPerson = new Person();
    		mPerson.setName("Bill");
    		mPerson.setAge(22);
    		
    		Bundle bundle = new Bundle();
    		bundle.putParcelable(KEY, mPerson);		// mPerson -> Parcelable

            Log.d(TAG, "mPerson=" + mPerson);
    		
    		Intent intent = new Intent(this, SubActivity.class);
    		intent.putExtras(bundle);
    		startActivity(intent);

            Log.d(TAG, "startActivity");
    	}
    	
    }
}

SubActivity

代码语言:javascript
复制
package com.learn;

import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;

public class SubActivity extends Activity {

	private static final String TAG = "Parcelable";
	
	private TextView tv;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

        Log.d(TAG, "SubActivity");
        
		Parcelable parcelable = getIntent().getParcelableExtra(MainActivity.KEY);
		Person mPerson = (Person)parcelable;		// Parcelable -> Person

        Log.d(TAG, "parcelable=" + parcelable + "; mPerson=" + mPerson);
        
		tv = (TextView)findViewById(R.id.tv);
		tv.setText("name=" + mPerson.getName() + "; age=" + mPerson.getAge());
	}
	
}

Person

代码语言:javascript
复制
package com.learn;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Person implements Parcelable{

	private static final String TAG = "Parcelable";
	
	private String name;
	private int age;
	
	public Person(){
		
	}

	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return this.name;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return this.age;
	}
	
	
	public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {

		@Override
		public Person createFromParcel(Parcel source) {

            Log.d(TAG, "createFromParcel(Parcel source)");
            
			Person mPerson = new Person();
			
			mPerson.name = source.readString();
			mPerson.age = source.readInt();
			
			return mPerson;
		}

		@Override
		public Person[] newArray(int size) {

            Log.d(TAG, "newArray(int size)");
            
			return new Person[size];
		}
		
	};
	
	@Override
	public int describeContents() {

        Log.d(TAG, "describeContents()");
        
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {

        Log.d(TAG, "writeToParcel(Parcel dest, int flags)");
        
		dest.writeString(name);
		dest.writeInt(age);
	}
	
}

main.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    
	<TextView  
		android:id="@+id/tv"
    	android:layout_width="fill_parent" 
    	android:layout_height="wrap_content" 
    	android:text="@string/hello" />
    
    <Button android:id="@+id/btn"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:text="Parcelable" />
    
</LinearLayout>

Running Result

click, then

Log

代码语言:javascript
复制
D/Parcelable(  487): MainActivity
D/Parcelable(  487): onClick
D/Parcelable(  487): mPerson=com.learn.Person@40520b98
D/Parcelable(  487): writeToParcel(Parcel dest, int flags)
D/Parcelable(  487): startActivity
D/Parcelable(  487): SubActivity
D/Parcelable(  487): createFromParcel(Parcel source)
D/Parcelable(  487): parcelable=com.learn.Person@405269f8; mPerson=com.learn.Person@405269f8

Analyse

writeToParcel(Parcel dest, int flags)         ----          bundle.putParcelable(KEY, mPerson)

createFromParcel(Parcel source)             ----          (Person)getIntent().getParcelableExtra(MainActivity.KEY)

source                                                        ----          dest

Download

Parcelable - How to do that in Android

Writing Parcelable classes for Android

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011年11月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档