MainActivity如下:
[java]
package cc.testparcelable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
/**
* Demo描述:
* 利用Parcelable在Activity之间传递自定义对象
*/
public class MainActivity extends Activity {
private Button mButton;
private final String key="testparcelable";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mButton=(Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Worker worker=new Worker(9527, "zxx");
Bundle bundle=new Bundle();
bundle.putParcelable(key, worker);
Intent intent=new Intent(MainActivity.this, AnotherActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
AnotherActivity如下:
[java]
package cc.testparcelable;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Parcelable;
public class AnotherActivity extends Activity {
private TextView mTextView;
private final String key="testparcelable";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.another);
init();
}
private void init() {
mTextView=(TextView) findViewById(R.id.textView);
Parcelable parcelable=this.getIntent().getParcelableExtra(key);
Worker worker=(Worker) parcelable;
mTextView.setText("Parcelable传递过来的数据为:\n"+"id="+worker.getId()+" name="+worker.getName());
}
}
Worker如下:
[java]
package cc.testparcelable;
import android.os.Parcel;
import android.os.Parcelable;
/**
* 要传递自定义类型,应让自定义类型支持parcelable协议,
*
* 实现步骤如下:
* 1>自定义类型必须实现Parcelable接口,并且实现Parcelable接口的public void writeToParcel(Parcel dest, int flags)方法 .
* 2>自定义类型中必须含有一个名称为CREATOR的静态成员,该成员对象要求实现Parcelable.Creator接口及其方法.
*
* Parcelable接口的作用:
* 实现了Parcelable接口的实例可以将自身的状态信息(状态信息通常指的是各成员变量的值)写入Parcel
* 也可以从Parcel中恢复其状态. 所以使用Parcel用来完成数据的序列化传递.
*/
public class Worker implements Parcelable {
private Integer id;
private String name;
public Worker() {
super();
}
public Worker(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Worker [id=" + id + ", name=" + name + "]";
}
/////////////////////////////////////////////////////////////
//对象在Parcelable中的编码形式
@Override
public int describeContents() {
return 0;
}
//把javaBean中的数据写到Parcel
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(this.id);
parcel.writeString(this.name);
}
//添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Cre
补充:移动开发 , Android ,