gpt4 book ai didi

android - 将对象传递给其他 Activity

转载 作者:行者123 更新时间:2023-11-30 01:33:26 26 4
gpt4 key购买 nike

我对将对象发送到其他 Activity 有疑问。我不确定我在做什么。所以我在 MainActivity 中有对象 Player

final Player player = new Player("Player", 150);

我有一个单独的 Player 类,带有简单的构造函数

public class Player {

private String playerName;
private double playerCash;

Player(String playerName, double playerCash)
{
this.playerName = playerName;
this.playerCash = playerCash;
}

我有第二个 Activity ,我想在其中使用 Player 对象。我用这段代码在 MainActivity 中做了一个按钮

 mButton = (Button) findViewById(R.id.mButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("player", player);
startActivity(intent);
}
});

现在我遇到了“无法解析方法 putExtra”的问题。我究竟做错了什么?我只想要一个 Player 对象并想在多个 Activity 中使用它,但不知道如何使用。对于任何帮助,非常感谢 ;)

最佳答案

上面答案中提到的所有内容,都非常清楚地描述了解决方案。这是代码:

public class Player implements Parcelable{
private String playerName;
private double playerCash;

// Constructor
public Player(String playerName, double playerCash){
this.playerName = playerName;
this.playerCash = playerCash;
}
// Implement Getter and setter methods


// Parcelling part
public Player(Parcel in){
this.playerName = in.readString();
this.playerCash = in.readDouble();
}

@Оverride
public int describeContents(){
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(playerName);
dest.writeDouble(playerCash);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Player createFromParcel(Parcel in) {
return new Player(in);
}

public Player[] newArray(int size) {
return new Player[size];
}
};
}

关于android - 将对象传递给其他 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com