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/