【问题标题】:Pass custom class instance between activities在活动之间传递自定义类实例
【发布时间】:2015-11-11 12:05:41
【问题描述】:

我有一个自定义类“游戏”,我在活动代码顶部初始化。然后我去另一个活动,通常我传递数组列表等,但我想传递我的自定义类.....

我的自定义类“游戏”是一堆带有 getter 和 setter 方法的字符串和数组列表。

我得到一个

游戏不是可打包或可序列化的对象

当我尝试将其添加到意图时出错。有什么想法我可以在这里做什么?

//Init Instance of Game class
Game newGame = new Game();

设置我的听众。它适用于

//Setup onclick listeners
text.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent i = new Intent(this_Activity.this, next_Activity.class);
        i.putExtra("players", myList);
        i.putExtra("newGame", (Parcelable) newGame);
        startActivityForResult(i, 0);
    }
});

【问题讨论】:

标签: android android-intent serialization parcelable


【解决方案1】:

另外,你的类Game可以实现接口Serializable

public class Game implements Serializable {
    ...
}

您必须在第一个活动中更改侦听器:

text.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent i = new Intent(this_Activity.this, next_Activity.class);
        i.putExtra("players", myList);
        i.putExtra("newGame", newGame);
        startActivityForResult(i, 0);
    }
});

并在next_Activity中更改方法onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Game newGame = (Game) getIntent().getExtras().getSerializable("newGame");
}

【讨论】:

  • 这是一个绝妙、全面而简洁的答案。谢谢亚瑟。
【解决方案2】:

游戏类需要实现 Parcelable。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多