gpt4 book ai didi

java - Intent 传递数据不成功

转载 作者:行者123 更新时间:2023-11-29 20:26:05 27 4
gpt4 key购买 nike

我正在制作一个游戏的得分列表,我使用下面的代码将得分时间传递给 ScoreActivity,但我不知道为什么它只显示默认数字“1”

long timeSpent = System.currentTimeMillis() - initialTime;
timeSpent = (long) (timeSpent / 1000.0);
int apple = (int)timeSpent;
Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);

AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this).create();
alertDialog.setTitle("Game Over!");
alertDialog.setMessage(" Total time " + String.valueOf(timeSpent));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"Exit", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

Intent i =new Intent(getContext(), ScoreActivity.class);
getContext().startActivity(i);
}

在得分 Activity 中

TextView myText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
myText = (TextView)findViewById(R.id.text444);
Intent scoreIntent = getIntent();
int rating = scoreIntent.getIntExtra("score", 1);
String str = Integer.toString(rating);
myText.setText(rating);
}

最佳答案

它显示默认值,因为您创建了一个 Intent 并在其中添加了额外内容

Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);

没错,但是当您开始 Activity 时,您使用了另一个 Intent

Intent i =new Intent(getContext(), ScoreActivity.class);
getContext().startActivity(i);

并且 apple 的值不在新的 Intent i 中,所以一个解决方案是让你的 Intent scoreIntent final 您可以从 onClick() 方法访问它,例如:

final Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);

onClick() 开始

getContext().startActivity(scoreIntent );

关于java - Intent 传递数据不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549733/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com