如何在多个类中使用对象?

时间:2016-02-21 22:38:25

标签: android

我正在与此争斗一段时间,但仍然不知道如何使其发挥作用。所以我有带有构造函数的类Player

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

在MainActivity中我制作了一个玩家对象

Player player = new Player("player", 100);

现在在SecondActivity的TextView中我想使用

playerCash = (TextView) findViewById(R.id.playerCash);
    playerCash.setText(player.getPlayerCash());

有人能解释我怎么能让它有效吗?我得到无法解决符号播放器。提前致谢

2 个答案:

答案 0 :(得分:0)

我不确定你发布的内容是你的整个课程,还是你忽略了它的一部分。我会写这个答案,假设那是你的全班。

所以,这是交易:您需要在类中创建方法,以便从中获取和设置数据。

public class Player() implements Parcelable {

    private String playerName;
    private String playerCash;

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

    public String getPlayerName() {
        return playerName;
    }

    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }

    public String getPlayerCash() {
        return playerCash;
    }

    public void setPlayerCash(String playerCash) {
        this.playerCash = playerCash;
    }

    public Player(Parcel in) {
        String[] data = new String[2];
        in.readStringArray(data);
        this.playerData = data[0];
        this.playerCash = data[1];
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] {this.playerName,
                                           this.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];
       }
    };
}

修改

我没有读过您说要在活动之间分享的部分。我之所以注意到它,是因为有人提到实施了Parcelable,这确实有助于解决问题。

无论如何,我编辑了我的代码来实现它。

要在活动之间共享数据,您还需要一个意图,并且您可以在那里共享存储在您的Player类中的数据:

Intent i = new Intent();
i.putExtra("player", new Player("Jhon", "Over 9000!");

在你的第二个活动中,为了得到它你会做:

Bundle b = getIntent().getExtras();
Player player = b.getParcelable("player");

希望有所帮助。

答案 1 :(得分:0)

您可以为Player类实施Parcelable接口,然后将其实例从MainActivity传递到IntentSecondActivity