[英]How to pass an integer variable to another class
我有一堂课的公共诠释结果; 在游戏的稍后部分,我使用该变量存储用户得分。 现在,我有另一个名为Result的活动/类,并且在该活动中有一个textView,我需要使用Result变量对该textView进行sexText。 我创建了一个游戏类的实例,并在Result类中将其命名为g,然后我做了类似的事情:
score = (TextView) findViewById(R.id.tvResult);
score.setText("Game over!\nYour score is:\n" + k.Result);
但是我总是得到0。我认为这是因为我得到了变量的默认值,而不是真实值。 游戏结束后,如何传递添加到变量中的最终值?
我还在游戏活动中尝试过此操作,以将变量作为意图传递:
Intent i = new Intent(Quiz.this, Result.class);
i.putExtra("newResultVariable", Result);
startActivity(i);
也得到0。
将变量作为意图传递。
要使用任何语言进行编程,都应遵循语言的命名约定。
在Quiz.java中
Intent intent = new Intent(context,Result.class);
intent.putExtra("newResultVariable", result);
startActivity(intent);
在Result.java中获取价值。
public void onCreate(Bundle bundle) {
....
int score = 0;
TextView scoreTextView = (TextView) findViewById(R.id.tvResult);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
score = extras.getInt("newResultVariable", 0);
}
scoreTextView.setText("Game over!\nYour score is:\n" + score);
....
}
首先,您给定的变量名称不好,因为它没有遵循CamelCase
因此它应该是结果而不是Result.Now尝试如下:
参加测验活动
Intent intent = new Intent(getApplicationContext(),Result.class);
intent.putExtra("result_variable", result);
startActivity(intent);
结果活动
getIntent().getIntExtra("result_variable", 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.