Java 为什么可以';我不能让我的听众去工作吗?为什么Eclipse中的这个代码片段会给出一个;是否应改为“ClassHeader”;?

Java 为什么可以';我不能让我的听众去工作吗?为什么Eclipse中的这个代码片段会给出一个;是否应改为“ClassHeader”;?,java,android,Java,Android,您不能像这里所做的那样在类之外声明变量。相反,您应该在类或方法中声明它: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.view.View; import android.view.View.OnClickListener; //Create an anonymous i

您不能像这里所做的那样在类之外声明变量。相反,您应该在类或方法中声明它:

package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;


//Create an anonymous implementation of OnClickListener
private OnClickListener buttonPress = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
        // setContentView(R.layout.panic);
    }
}



public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button myPanicButton = (Button)findViewById(R.id.PanicButton);
    setContentView(R.layout.main);
    myPanicButton.setOnClickListener(buttonPress);
    }
};


你太棒了。谢谢。成功了。我发誓我的课本显示了我的错误方式。吓人的!
public class HelloAndroid extends Activity {
    //Create an anonymous implementation of OnClickListener
    private OnClickListener buttonPress = new OnClickListener() {
        public void onClick(View v) {
          // do something when the button is clicked
            // setContentView(R.layout.panic);
        }
    }
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button myPanicButton = (Button)findViewById(R.id.PanicButton);
        setContentView(R.layout.main);
        myPanicButton.setOnClickListener(buttonPress);
    }
};
public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button myPanicButton = (Button)findViewById(R.id.PanicButton);
        setContentView(R.layout.main);

        //Create an anonymous implementation of OnClickListener
        OnClickListener buttonPress = new OnClickListener() {
            public void onClick(View v) {
              // do something when the button is clicked
                // setContentView(R.layout.panic);
            }
        }
        myPanicButton.setOnClickListener(buttonPress);
    }
};