1

我有以下内容int

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setContentView(R.layout.activity_score);
    // Show the Up button in the action bar.
    setupActionBar();
    Intent i = getIntent();
    String max = i.getStringExtra(MainActivity.EXTRA_MAX);
    final int maxInt = Integer.parseInt(max);

我想从这里访问它:

public void plus1 (View V)
{
    maxInt ++;
}

但是我得到一个错误,即使不使用final,当在int类内时:

public class ScoreActivity extends Activity {

我撞车了。

4

3 回答 3

2

您的应用程序崩溃,因为maxIntplus1 中的变量未定义。maxInt的范围是本地的onCreate。变量也final类似于constantC 中的变量。它们只能在初始化时获取值,这意味着您无法更改它们的值。

你的 maxInt 不应该是最终的,应该是一个全局变量:

public class ScoreActivity extends Activity {

    int maxInt;

    protected void onCreate(Bundle savedInstanceState) { 
        ...
        maxInt = Integer.parseInt(max);
        ...
    }

    public void plus1 (View V) {
        maxInt ++;
    }

    ...
}
于 2013-07-14T16:20:35.260 回答
1

您无法maxInt在其他方法中访问的原因是您在 onCreate 方法中创建了它。它的作用域是该方法的本地范围,因此该类的其余部分看不到它。此外,一旦 OnCreate() 超出范围,maxInt将被销毁,其中存储的数据将丢失。

如果您想访问整个类的对象/变量,请将其设为global.

int maxInt;

protected void onCreate(Bundle savedInstanceState) { 

    maxInt = Integer.parseInt(max);
...
....
}

public void plus1 (View V) {
  .....   
  maxInt ++;
    ..........
}
于 2013-07-14T16:25:44.283 回答
1

int maxInt;在课前onCreate()但在课内声明

更改您的代码

final int maxInt = Integer.parseInt(max);

maxInt = Integer.parseInt(max);
于 2013-07-14T16:24:23.347 回答