为什么我不能让我的OnClickListener工作?为什么Eclipse中的这段代码片段会给出“预期的ClassHeader”?

时间:2011-06-19 13:47:47

标签: 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 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);
    }
};

1 个答案:

答案 0 :(得分:1)

您不能像在此处一样在类之外声明变量。相反,您应该在类内或方法内声明它:

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);
    }
};