java - 如何将整型变量传递给另一个类

标签 java android variables

我有一个带有 public int Result 的类;稍后在游戏中,我使用该变量来存储用户获得的点数。现在,我有另一个名为 Result 的 Activity/类,并且该 Activity 中有一个 textView,我需要将 Result 变量用于 sexText 到该 textView。我创建了游戏类的一个实例,并在 Result 类中将其命名为 g,然后我做了如下操作:

score = (TextView) findViewById(R.id.tvResult);
        score.setText("Game over!\nYour score is:\n" + k.Result);

但我总是得到0。我认为这是因为我得到的是变量的默认值,而不是真实的值。游戏结束后如何将添加到变量的最终值传递给变量?

我还在游戏 Activity 中尝试过此操作,将变量作为 Intent 传递:

Intent i = new Intent(Quiz.this, Result.class);
            i.putExtra("newResultVariable", Result);
            startActivity(i);

也得到0。

最佳答案

To pass the variable as an intent.

要使用任何语言进行编程,您应该遵循语言的命名约定。

在 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); 
     ....
}

关于java - 如何将整型变量传递给另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15188594/

相关文章:

java - Spring 问题 : Error creating beans and Injection of autowired dependencies failed

android - ListView 示例在结果 View 中复制联系人

android - AlertDialog 中的资源 ID #0x0

C++ 变量类型 - 值

JavaScript:使用函数参数定义变量名

java - resultSet.rowUpdated() 抛出 createSQLFeatureNotSupportedException

java - Swing 布局: Prevent my components from moving around

java - 你能在 Java 中获取变量的先前值吗?

java - 无法解析 com.google.android.gms :play-services-ads:19. 1.0

java - 如何先更新变量然后在java中执行其余代码