我试图将一个 int 值从当前活动发送到新活动,这是当前活动中的部分。
dialog.setPositiveButton("4 players", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Start a new game!", Toast.LENGTH_SHORT).show();
// need send extra value to PlayerBoardActivity to decide how many buttons I should have
Intent intent = new Intent(MainActivity.this,
PlayBoardActivity.class);
intent.putExtra(PLAYER_NO, 4);
startActivity(intent);
}
});
dialog.setNegativeButton("2 players", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Start a new game!", Toast.LENGTH_SHORT).show();
// need send extra value to PlayerBoardActivity to decide how many buttons I should have
Intent intent = new Intent(MainActivity.this,
PlayBoardActivity.class);
intent.putExtra(PLAYER_NO, 2);
startActivity(intent);
}
});
问题是,我为新活动创建了 2 个布局文件。例如,当我在对话框中按下否定按钮时,我想要的是让新活动(在我的例子中为 PlayerBoardActivity)加载与我发送的值相对应的布局文件“intent.putExtra(PLAYER_NO, 2);”
新活动中的代码是
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PLAYER_NO = "the number of players";
Bundle b = getIntent().getExtras();
int a = b.getInt(PLAYER_NO);
if (b != null) {
if (a == 2) {
setContentView(R.layout.two_player);
}
if(a == 4){
setContentView(R.layout.four_player);
}
}
}
我想知道我是否可以通过这种方式加载不同的布局文件?或者我的问题有没有更好的解决方案。
谢谢大家。