在活动之间传递自定义 class 实例
Pass custom class instance between activities
我有一个自定义 class 'Game',我在 activity 代码的顶部初始化。然后我转到另一个 activity,通常我传递 arraylists 等,但我想转到传递我的自定义 class.....
我的习惯 class 'game' 是一堆带有 getter 和 setter 方法的字符串和数组列表。
我得到一个
Game is not a parcelable or serializable object
尝试将其添加到意图时出错。我可以在这里做什么?
//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);
}
});
游戏class需要实现Parcelable。
此外,您的 class Game
可能会实现接口 Serializable
:
public class Game implements Serializable {
...
}
您必须先更改侦听器 activity:
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");
}
我有一个自定义 class 'Game',我在 activity 代码的顶部初始化。然后我转到另一个 activity,通常我传递 arraylists 等,但我想转到传递我的自定义 class.....
我的习惯 class 'game' 是一堆带有 getter 和 setter 方法的字符串和数组列表。
我得到一个
Game is not a parcelable or serializable object
尝试将其添加到意图时出错。我可以在这里做什么?
//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);
}
});
游戏class需要实现Parcelable。
此外,您的 class Game
可能会实现接口 Serializable
:
public class Game implements Serializable {
...
}
您必须先更改侦听器 activity:
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");
}