将int变量传递给另一个类时遇到问题。我已经尝试了很多传递这个变量的方法,但没有一个有效。帮助我将变量randomNum从MainActivity传递给HistoryActivity。谢谢!
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
int min, max;
max = 1;
min = 0;
int randomNum = min + (int) (Math.random() * ((max - min) + 1));
int backgroundImages[] = {R.drawable.background1,
R.drawable.background2};
final Drawable backgroundImage = getResources().getDrawable(
backgroundImages[randomNum]);
linearLayoutBackground.setBackgroundDrawable(backgroundImage);
// // WHAT TO DO NOW POGA
buttonWhatToDoNow.setOnClickListener(new View.OnClickListener() {
.........
}
});
buttonHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, HistoryActivity.class);
startActivity(i);
finish();
}
});
}
}
public class HistoryActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
.......
randomNum =..............;
int backgroundImages[] = {R.drawable.background1,
R.drawable.background2};
final Drawable backgroundImage = getResources().getDrawable(
backgroundImages[randomNum]);
linearLayoutBackground.setBackgroundDrawable(backgroundImage);
}
}
答案 0 :(得分:1)
Intent i = new Intent(MainActivity.this, HistoryActivity.class);
i.putExtra("intVariableName", randomNum);
startActivity(i);
历史活动 in on create method例如
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
答案 1 :(得分:0)
假设我们有2个课程和2个活动。
如果你希望你的值在HistoryActivity中,只需在Historyactivity的类中声明值(适用于第二页),并从第一个活动到historyactivity制作一个意图....就是这样!! !!
答案 2 :(得分:0)
在您的onclick中:
//onclick MainActivity
Bundle bundle = new Bundle();
bundle.putInt("key", randomInt);
Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
intent.putExtras(bundle);
finish();
startActivity(intent);
//then in your HistoryActivity onCreate
int randomNum = getIntent().getExtras().getInt("key");`