【发布时间】:2013-08-29 22:56:01
【问题描述】:
我有一个应用程序,我试图在活动之间传递类对象。我就是这样做的。
类:
public class Player implements Serializable{
public String name;
public int score;
public static final int serialVersionUID = 12345;
}
将类对象添加到额外的意图中:
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
Player newPlayer = new Player();
newPlayer.name = text;
newPlayer.score = 0;
players.add(text);
playerScores.add(newPlayer);
zacniIgro.putExtra("playerScores", (ArrayList<Player>) playerScores);
zacniIgro.putStringArrayListExtra("players", (ArrayList<String>) players);
return newTextView;
}
在另一个活动中获得额外的意图:
playersData = getIntent();
playerScoresData = getIntent();
players = playersData.getStringArrayListExtra("players");
playerScores = (ArrayList<Player>) playerScoresData.getSerializableExtra("playerScores");
我现在如何操作这些可序列化的对象?我想从 playerScores 中获取某个元素并对其进行操作。例如:我想从中取出索引为 0 的元素,然后使用它的名称和分数进行操作。
【问题讨论】:
-
不确定这是否是您要问的:
playerScores.get(0)将为您提供Player对象。playerObj.name和playerObj.score会告诉你它的名字和分数。 -
在 Android 上你应该使用 Parcelable,而不是 Serializable
-
@user2558882 但如何将“playerScores.get(0)”分配给 Player 对象?
-
Player playerObj = playerScores.get(0);。获取名称:String nameOfPlayer = playerObj.name;。获取分数:int scoreForPlayer = playerObj.score. -
@user2558882 非常感谢!这就是我要找的。您可以将其发布为答案,我会接受它
标签: java android eclipse serialization