我在bundle中保存实例的代码正在运行,但我不明白它是如何工作的。
如果我旋转设备,点击保存在捆绑中的按钮后的学生姓名。
这是我的班级
package com.example.app;
import android.os.Parcel;
import android.os.Parcelable;
public class Student implements Parcelable {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getDisplayedName()
{
return lastName + " " + firstName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
}
你可以在这里看到我没有在方法writeToParcel中编写任何代码,也没有在类中创建CREATOR字段。 但它正在我的所有设备上工作,包括模拟器设备
这是我的活动代码
package com.example.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
private Student student;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button generateButton = (Button) findViewById(R.id.generate);
generateButton.setOnClickListener(generateStudentName);
if (savedInstanceState != null) {
student = savedInstanceState.getParcelable("student");
writeStudent();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable("student", student);
super.onSaveInstanceState(outState);
}
private void writeStudent() {
final TextView studentName = (TextView) findViewById(R.id.student_name);
studentName.setText(student.getDisplayedName());
}
private View.OnClickListener generateStudentName = new View.OnClickListener() {
@Override
public void onClick(View v) {
Random randomGenerator = new Random();
student = new Student(String.valueOf(randomGenerator.nextInt(10000)), String.valueOf(randomGenerator.nextInt(10000)));
writeStudent();
}
};
}
为什么会这样?