当前位置 : 主页 > 手机开发 > android >

android – 为什么onClickListener不能在onCreate方法之外工作?

来源:互联网 收集:自由互联 发布时间:2021-06-11
当我尝试将onClickListener方法用于任何onCreate或onPause或onAnything方法之外的按钮变量时,它不起作用.我甚至无法在“onAnything”方法之外设置按钮变量的值.帮助会很棒. 谢谢! public class Sta
当我尝试将onClickListener方法用于任何onCreate或onPause或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");

  }

}
我注意到你的代码的一件事是你在声明它们时初始化你的视图,这是在你设置内容视图之前.在您执行此操作之前,按ID查找视图将无效.改变它,所以你声明它们就像

Button add;
Button sub;

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

此外,您看到的错误消息是因为您无法在方法之外执行该语句.无论如何你应该在onCreate里面做.

网友评论