2013-01-11 43 views
0

我是一個總的初學者,因此請在這個問題上與我相處。Android應用程序在恢復後丟失/改變狀態

這是我寫一個簡單的「捶鼴鼠」遊戲的悲傷嘗試。用戶界面由9個沒有標題的按鈕組成。計時器隨機選擇一個必須由用戶點擊的按鈕(按鈕獲得標題「X」)。如果用戶選擇正確的按鈕,他會得到10分。如果沒有及時點擊按鈕(或錯誤的按鈕),將從樂譜中減去10分。

正如你所看到的,我添加了一個OnClickListener到每個按鈕並刪除onCreate-Method中的初始標題(「Button1」,「Button2」...)。一切工作看起來都很好,直到我離開應用程序然後再回來。所有按鈕突然再次具有其初始標題。計時器仍然運行(每秒鐘降低分數),但沒有任何按鈕發生變化。

現在我知道這可能與活動生命週期有關,我已經閱讀了它。不幸的是,我的英語不是最好的,而且我對理解這個概念有點困難。也許有人願意簡單地向我解釋這一點?

public class MainActivity extends Activity { 

private static int[]  buttons  = {R.id.button1, R.id.button2, ...}; 
private static List<Button> buttonlist = new ArrayList<Button>(); 

private static TextView  scoreboard; 
private static Timer  timer = new Timer(); 
private static int   score; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    scoreboard = (TextView) findViewById(R.id.textView1); 

    for (int i = 0; i < 9; i++) { 
     buttonlist.add((Button) findViewById(buttons[i])); 
     buttonlist.get(i).setText(""); 

     // add OnClickListener for each Button 
     ((Button) buttonlist.get(i)).setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       //if correct Button is pressed add 20 to score 
       if ("X".equals(((Button) v).getText().toString())) { 
        score += 20; 
        //and set button-text to "" again ... 
        ((Button) v).setText(""); 
       } 
       else { 
        score -= 10; 
       } 
      } 
     }); 

    } 
    // Start Game 
    timer.schedule(new MyTimerTask(), 0, 1000); 
} 

private class MyTimerTask extends TimerTask { 
    @Override 
    public void run() { 
     runOnUiThread(new Runnable() { 
      public void run() { 
       score -= 10; 
       scoreboard.setText("Your Score: " + score); 

       //clear buttons 
       for (int i = 0; i < 9; i++) 
        buttonlist.get(i).setText(""); 

       //pick random button as next target 
       buttonlist.get((int) (Math.random() * (9 - 1) + 1)).setText("X"); 
      } 
     }); 
    } 
} 



@Override 
protected void onResume() { 
    super.onResume(); 
    // Do something here? 
} 


... 

回答

1

一旦你離開你的活動,系統會調用按照您的活動方法:

的onPause 的onStop 的onDestroy

當你進入

您的活動類的實例將被銷燬

您再次將其重新創建,以下方法將被調用:

的onCreate 在onStart 的onResume

這是活動的生命週期看起來像你的情況(有一點了解詳情)

您的問題是,你的buttonList是靜態的,計時器和比分一起。即使你離開你的應用程序,系統也不會破壞你的應用程序進程,這樣所有的靜態變量都將保持不變。這意味着您的按鈕列表將包含來自之前活動實例的最初按鈕。

解決方法是不使用靜態關鍵字。如果要在退出活動後保留某些狀態,請查看onSaveInstanceState。此外 - 假設您的設備可以旋轉,這也將重新創建您的活動。

+0

感謝您的快速回復!我現在看起來更清楚:) – subarachnid

相關問題