1

保存实例后,我需要共享“int audio”到 check() 方法来执行几个操作。我有一个“信息”选项:当我点击我看到信息对话框并且我想听音频(当我点击“取消”时停止它)。但是当我旋转模拟器时,我有另一个音频明星。

int audio;
static int Info;

@Override
public void onCreate(Bundle savedInstanceState){ 
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
int Info = savedInstanceState.getInt("dialoginfo");
int audio = savedInstanceState.getInt("audio");
}

if(Info != 0)
  {
      Info();
}

private void Info(){
    Info = 1;
    sobCheck();
    LayoutInflater li = LayoutInflater.from(this);
    View view = li.inflate(R.layout.info, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(view).create();
    TextView text=(TextView) findViewById(R.id.infoView1);
    builder.setCancelable(false); 
    builder.setPositiveButton("Chiudi", new DialogInterface.OnClickListener() {  
           public void onClick(DialogInterface dialog, int id) {  
               Info = 0;
               mp.stop();
               mp.reset();
               mp.release();
                mp = null;
                audio = 0;                  
               dialog.cancel();
        }  
        });  
    builder.show();
        }


private void sobCheck(){
if (audio == 0){
mp = MediaPlayer.create(this, R.raw.sob);
mp.start();
audio = 1;
}



protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("audio", a);

旋转屏幕后,“音频”始终为“0”

4

3 回答 3

3

问题是您已经创建了本地范围的变量,这些变量在此处隐藏了您的应用程序级变量:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        int Info = savedInstanceState.getInt("dialoginfo");
        int audio = savedInstanceState.getInt("audio");
    }

    if (Info != 0) {
        Info();
    }
}

这声明并初始化了两个变量Infoaudio,它们的范围为您的 if 检查并在之后立即丢弃。它们实际上不会更改您在 onCreate 方法之外声明的应用程序级变量。尝试将其更改为:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        Info = savedInstanceState.getInt("dialoginfo");
        audio = savedInstanceState.getInt("audio");
    }

    if (Info != 0) {
        Info();
    }
}

这可以防止Infoaudio在您的本地范围内重新声明,而是应该导致您已经声明的变量被初始化。

于 2012-12-07T21:54:08.190 回答
1

您必须在 onCreate() 范围之外声明它:

int audio;

@Override
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        audio = savedInstanceState.getInt("audio");
}
于 2012-12-07T18:49:22.107 回答
0

您在方法中重新初始化“音频”。只需在分配音频值之前取出“int”。

于 2012-12-07T19:10:28.243 回答