2014年(5)
分类: Android平台
2014-06-16 08:33:34
1
2
3
4
5
6
7
8
9
10
|
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putParcelable("name", name);
fragment2.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment2)
.addToBackStack(null)
.commit();
|
1
|
ParcelableName name = getArguments().getParcelable("name");
|
Serializable用了很多反射,细心的人都知道,反射比正常的调用要慢100多倍
Serializable会创建很多临时对象,这些临时对象会导致很多次垃圾回收,影响效率
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public interface Parcelable {
public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;
public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;
public int describeContents();
public void writeToParcel(Parcel dest, int flags);
public interface Creator
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
public interface ClassLoaderCreator
public T createFromParcel(Parcel source, ClassLoader loader);
}
}
|
第一个方法返回数字,一般返回0就好,只有FileDescriptor有特殊,上面的常量有定义。至于这有什么用,我也没有找到相关的信息,如果有读者理解,请留言告知我。
第二个方法用于将对象写入到Parcel对象中。详见下面的例子。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableName implements Parcelable {
private String mSurname;
private String mGivenName;
public ParcelableName(String surname, String givenName) {
mSurname = surname;
mGivenName = givenName;
}
// 私有方法,因为我们不应该将参数是Parcel的构造函数暴露出去
private ParcelableName(Parcel source) {
this(source.readString(), source.readString());
}
@Override
public int describeContents() {
return 0;
}
public String getSurname() {
return mSurname;
}
public String getGivenName() {
return mGivenName;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mSurname);
dest.writeString(mGivenName);
}
// 通过这个接口来创建Parcel对象,调用了私有的构造函数
public static final Parcelable.Creator
= new Creator
@Override
public ParcelableName createFromParcel(Parcel source) {
return new ParcelableName(source);
}
@Override
public ParcelableName[] newArray(int size) {
return new ParcelableName[0];
}
};
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Parcel
public class Example {
String mSurname;
String mGivenName;
public Example(){ }
public Example(String surname, String givenName) {
mSurname = surname;
mGivenName = givenName;
}
public String getSurname() { return mSurname; }
public String getGivenName() { return mGivenName; }
}
|