2011-11-30 66 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

相关问题