0
我有一個應用程序,我試圖在活動之間傳遞類對象。這是我如何做的。如何從Serializable中獲取類對象?
類:
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'會給你它的名字和分數。 – Vikram
在Android上,您應該使用Parcelable,而不是Serializable –
@ user2558882,但是如何將「playerScores.get(0)」分配給Player對象? – Guy