java - 为什么我的 OnClickListener 无法工作?为什么 Eclipse 中的这段代码 fragment 会给出 "ClassHeader expected instead"?

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

最佳答案

您不能像在此处所做的那样在类外部声明变量。相反,您应该在类内部或方法内部声明它:

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

关于java - 为什么我的 OnClickListener 无法工作?为什么 Eclipse 中的这段代码 fragment 会给出 "ClassHeader expected instead"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6402718/

相关文章:

java - Java 准备语句中的通配符问题

android - AndEngine 示例不工作

java - Android 根据国家/地区运行不同的功能

android - 将字符串从一个方法传递到另一个android

Android套接字无法连接到服务器

java - 如何在外部添加.so文件

java通知所有: illegalMonitorStateException

java - 是否有重用 BufferedWriter 的模式?

java - java中使用amf3input反序列化amf二进制格式

android - 自定义 android 微调器