当我尝试将onClickListener
方法用于任何onCreate or onPause or onAnything
方法之外的变量按钮时,它不起作用。我甚至无法在“onAnything”方法之外设置按钮变量的值。帮助会很棒。
谢谢!
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");
}
}
答案 0 :(得分:4)
我注意到你的代码的一件事是你在声明它们时初始化你的视图,这是在你设置内容视图之前。在您执行此操作之前,按ID查找视图将无效。更改它,以便声明它们像
Button add;
Button sub;
...
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
此外,您看到的错误消息是因为您无法在方法之外执行该语句。无论如何,你应该在onCreate
内进行。
答案 1 :(得分:3)
您应该浏览此博客 - {{3p>