android - 为什么 onClickListener 在 onCreate 方法之外不起作用?

标签 android

<分区>

当我尝试对按钮使用 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");

  }

}

最佳答案

关于您的代码,我注意到一件事是您在声明 View 时初始化 View ,这是在设置内容 View 之前。在您这样做之前,按 ID 查找 View 将不起作用。改变它,这样你就可以像这样声明它们

Button add;
Button sub;

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

此外,您看到的错误消息是因为您无法在方法之外执行该语句。无论如何,您应该在 onCreate 中执行此操作。

关于android - 为什么 onClickListener 在 onCreate 方法之外不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321197/

相关文章:

android - ListView 的第一个条目对于 RTL 总是不正确

android - 蓝牙信标的替代品

android - 将 TabLayout 放在屏幕中间

android - 为什么 Images.Media.insertImage 返回 null

android - 在phonegap上使用android写入和读取.txt文件需要帮助

java - 如何移动操作栏中的标题选项卡指示器?

java - 在 doInBackground 方法中从另一个异步任务调用 AsyncTask?

android - 在android中为键入的字母着色

android - ViewPager 中的 ScrollView 在 Android 4.x 上不滚动

java - Android JSON only OBJECT Fetching with Iteration