2011-11-30 44 views
3

當我嘗試將onClickListener方法用於按鈕,在任何onCreate or onPause or onAnything方法之外的變量時,它都不起作用。我甚至不能在「onAnything」方法之外設置按鈕變量的值。幫助會很好。爲什麼onClickListener不能在onCreate方法之外工作?

謝謝!

public class StartingPoint extends Activity { 
/** Called when the activity is first created. */ 

int counter; 
Button add= (Button) findViewById(R.id.bAdd); 
Button sub= (Button) findViewById(R.id.bSub); 
TextView display= (TextView) findViewById(R.id.tvDisplay); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.main); 
    Log.i("phase", "on create"); 
    counter=0;  

    add.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      counter++; 
      display.setText(""+counter); 
      display.setTextSize(counter); 
      Log.i("phase", "add"); 
     } 
    }); 
    sub.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      counter--; 
      display.setText(""+counter); 
      display.setTextSize(counter); 
      display.setTextColor(Color.GREEN); 
      Log.i("phase", "sub"); 
     } 
    }); 

} 

@Override 
protected void onStart() { 
    // TODO Auto-generated method stub 
    super.onStart(); 
    Log.i("phase", "on start"); 
    SharedPreferences prefs = getPreferences(0); 
    int getfromfile = prefs.getInt("counter_store", 1); 
    counter=getfromfile; 
    display.setText(""+getfromfile); 
    display.setTextSize(getfromfile); 
} 

@Override 
protected void onStop() { 
    // TODO Auto-generated method stub 
    super.onStop(); 
    Log.i("phase", "on stop"); 
    SharedPreferences.Editor editor = getPreferences(0).edit(); 
    editor.putInt("counter_store", counter); 
    editor.commit(); 
} 

@Override 
protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    counter=0; 
    Log.i("phase", "on destroy"); 

    } 

} 
+4

你是什麼意思不起作用?你有錯誤嗎?顯示你正在嘗試做什麼的郵政編碼 – Craigy

+1

顯示你的代碼。 –

+2

所以模糊的問題... –

回答

4

有一件事我注意到你的代碼是要初始化你的意見時,你聲明它們,這是你設置的內容視圖之前。通過ID查找視圖將不會工作,直到你這樣做。更改它,以便您聲明它們像

Button add; 
Button sub; 

... 
    setContentView(R.layout.main); 
    add = (Button) findViewById(R.id.bAdd); 
    sub = (Button) findViewById(R.id.bSub); 

此外,您看到的錯誤消息是因爲您不能在方法外執行該語句。無論如何,你應該在onCreate之內。

+1

爲什麼它不能在方法之外工作?對不起,我想了解它,而不是將其作爲面值。謝謝! – user947659

+0

出於同樣的原因,除了初始化變量外,您不能在Java中的方法之外調用任何方法。此外,在你調用'setContentView'後,你想在'onCreate'中設置'onClickListener',它允許你使用'findViewById'來獲取按鈕。 – Craigy

+0

很酷,感謝您的信息! – user947659

相關問題