创建实现 Parcelable 的 class 的对象
Create object of class that implements Parcelable
您如何实际创建一个 class 的对象来实现 Parcelable?网上有很多示例可以准确显示 class 应该是什么样子,但我似乎无法找到有关如何创建对象的信息。
如果我有一个实现了 Parcelable 的 class,并且构造函数如下所示:
public class ResultForTeam implements Parcelable
{
String playerA, playerB, teamA, teamB, scores;
int playerA_games, playerB_games;
public ResultForTeam(Parcel in)
{
this.playerA = in.readString();
this.playerB = in.readString();
this.teamA = in.readString();
this.teamB = in.readString();
this.scores = in.readString();
this.playerA_games = in.readInt();
this.playerB_games = in.readInt();
}
然后如何在我的代码中的其他地方创建此 class 的对象?
在我实现Parcelable之前,它曾经是这样的。
ResultForTeam newResult = new ResultForTeam(playerA, playerB, teamA, teamB, scores, playerA_games, playerB_games);
您可以保留旧的构造函数和这个重载的构造函数。您还需要实施 describeContents()
和 writeToParcel()
方法。不要忘记也写静态 CREATOR
字段。然后您将能够像往常一样使用 class 并将其与 Parcel
.
一起使用
您如何实际创建一个 class 的对象来实现 Parcelable?网上有很多示例可以准确显示 class 应该是什么样子,但我似乎无法找到有关如何创建对象的信息。
如果我有一个实现了 Parcelable 的 class,并且构造函数如下所示:
public class ResultForTeam implements Parcelable
{
String playerA, playerB, teamA, teamB, scores;
int playerA_games, playerB_games;
public ResultForTeam(Parcel in)
{
this.playerA = in.readString();
this.playerB = in.readString();
this.teamA = in.readString();
this.teamB = in.readString();
this.scores = in.readString();
this.playerA_games = in.readInt();
this.playerB_games = in.readInt();
}
然后如何在我的代码中的其他地方创建此 class 的对象? 在我实现Parcelable之前,它曾经是这样的。
ResultForTeam newResult = new ResultForTeam(playerA, playerB, teamA, teamB, scores, playerA_games, playerB_games);
您可以保留旧的构造函数和这个重载的构造函数。您还需要实施 describeContents()
和 writeToParcel()
方法。不要忘记也写静态 CREATOR
字段。然后您将能够像往常一样使用 class 并将其与 Parcel
.