我有一个应用程序,我试图在活动之间传递类对象。这就是我的做法。
类别:
public class Player implements Serializable{
public String name;
public int score;
public static final int serialVersionUID = 12345;
}
将class对象置于intent extra:
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获取元素,然后使用它的名称和分数进行操作。
答案 0 :(得分:0)
playerScores = (ArrayList<Player>) playerScoresData.getSerializableExtra("playerScores");
从Player
获取playerScores
个对象:
Player playerObj = playerScores.get(index);
玩家的名字可以通过以下方式访问:
String nameOfPlayer = playerObj.name;
获得分数:
int scoreForPlayer = playerObj.score;
正如Marcin建议的那样,使用Parcelable
代替Serializable
。序列化非常慢。比较:Parcelable vs Serializable
更多信息:Benefit of using Parcelable instead of serializing object