当我尝试将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");
}
}
你是什么意思不起作用?你有错误吗?显示你正在尝试做什么的邮政编码 – Craigy
显示你的代码。 –
所以模糊的问题... –