編輯:關於 Android 程式設計
在 Activity 之間傳遞物件,Android 提供兩條路:Serializable 與 Parcelable。前者是 Java SE 本身就有的機制,後者是 Android 專屬的設計。
就實作難度而言,Serializable 只要實作 getter/setter 並宣告介面即可;Parcelable 則需要多寫幾個方法。
實體類別:
package com.example.objecttrandemo;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = -7060210544600464481L;
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; }
}
版面檔:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="android object trance" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Serializable" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Parcelable" />
</LinearLayout>
主 Activity:
package com.example.objecttrandemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ObjectTranDemo extends Activity implements OnClickListener {
private Button sButton, pButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
}
public void setupViews() {
sButton = (Button) findViewById(R.id.button1);
pButton = (Button) findViewById(R.id.button2);
sButton.setOnClickListener(this);
pButton.setOnClickListener(this);
}
// 以 Serializable 傳遞
public void SerializeMethod() {
Person mPerson = new Person();
mPerson.setName("durant");
mPerson.setAge(25);
Intent mIntent = new Intent(this, ObjectTranDemo1.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable("mPerson", mPerson);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
// 以 Parcelable 傳遞
public void PacelableMethod() {
Book mBook = new Book();
mBook.setBookName("a man from mars");
mBook.setAuthor("james");
mBook.setPublishTime(2014);
Intent mIntent = new Intent(this, ObjectTranDemo2.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable("mBook", mBook);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
@Override
public void onClick(View v) {
if (v == sButton) {
SerializeMethod();
} else {
PacelableMethod();
}
}
}
接收端:
package com.example.objecttrandemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ObjectTranDemo1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView mTextView = new TextView(this);
Person mPerson = (Person) getIntent().getSerializableExtra("mPerson");
mTextView.setText("You name is: " + mPerson.getName()
+ "\n" + "You age is: " + mPerson.getAge());
setContentView(mTextView);
}
}
別忘了在 AndroidManifest.xml 註冊新的 Activity:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.objecttrandemo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<application android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name="com.example.objecttrandemo.ObjectTranDemo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ObjectTranDemo1"></activity>
<activity android:name=".ObjectTranDemo2"></activity>
</application>
</manifest>
Parcelable 介面。writeToParcel(),把物件資料寫進 Parcel,也就是打包要傳的內容。describeContents(),一般回傳 0 即可。CREATOR 並實作 Parcelable.Creator 介面。關於 CREATOR 有幾個硬性規定:public static final 一個都不能少,名稱必須是大寫的 CREATOR 且不可更改。介面中的兩個方法分別是 createFromParcel(Parcel in)(從 Parcel 讀回資料並封裝成物件)與 newArray(int size)(建立長度為 size 的陣列,一行 return new T[size] 即可)。
一句話總結:用 writeToParcel() 把物件寫成 Parcel,再用 createFromParcel() 還原回物件。可以把 Parcel 想成一條資料流,寫入與讀出的順序必須完全一致,否則欄位就會錯位。
Book.java:
package com.example.objecttrandemo;
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
private String bookName;
private String author;
private int publishTime;
public String getBookName() { return bookName; }
public void setBookName(String bookName) { this.bookName = bookName; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public int getPublishTime() { return publishTime; }
public void setPublishTime(int publishTime) { this.publishTime = publishTime; }
@Override
public int describeContents() {
return 0;
}
// 注意:這裡的順序必須與 createFromParcel 完全一致
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(bookName);
parcel.writeString(author);
parcel.writeInt(publishTime);
}
public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book[] newArray(int size) {
return new Book[size];
}
@Override
public Book createFromParcel(Parcel source) {
Book mBook = new Book();
mBook.bookName = source.readString();
mBook.author = source.readString();
mBook.publishTime = source.readInt();
return mBook;
}
};
}
顯示 Parcelable 資料的 Activity:
package com.example.objecttrandemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ObjectTranDemo2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView mTextView = new TextView(this);
Book mBook = (Book) getIntent().getParcelableExtra("mBook");
mTextView.setText("Book name is: " + mBook.getBookName()
+ "\n" + "Author is: " + mBook.getAuthor()
+ "\n" + "PublishTime is: " + mBook.getPublishTime());
setContentView(mTextView);
}
}
實務上還有一個省事的選項:若欄位都是基本型別,用 Bundle 直接 putString、putInt 反而最直觀;只有在需要傳遞整組結構化資料時,才值得付出 Parcelable 的實作成本。
Android ImageView 圓角與圓形圖片實作:Xfermode 與自訂 View
在 Android 介面設計中,頭像、卡片圖示常需要圓形或圓角效果。常見做法有兩種:利用 Xfermode 進行圖層合成,或透過 BitmapShader 搭配自訂 Vi
用 ViewPager 實作底部圓點導航與 Fragment 頁面切換
前一篇我們用 ViewPager 搭配 Fragment 做出了頂部滑塊跟手的滑動效果。本篇換個方向,實作底部圓點指示器,並示範滑動頁面內的控件如何監聽事件,以及 Fra
Android 消息處理機制全解:Looper、MessageQueue 與 Handler
一、C++ 層的 Looper Looper 提供的能力 Looper 類(system/core/libutils/Looper.cpp)提供了 pollOnce()
Fragment 管理與重疊怪象:add/hide 與 replace 該怎麼選
一、Fragment 是什麼 自從 3.0 引入 Fragment 之後,專案裡用到它的比例越來越高,最典型的場景就是底部 tab 切換內容。首頁的每一個 navigat