[英]Why can't I get my OnClickListener to work? Why would this code fragment in Eclipse give a “ClassHeader expected instead”?
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);
}
};
You cannot declare variables outside of your class, as you have done here. 您不能像在此所做的那样在类之外声明变量。 Instead, you should declare it either inside the class or inside a method:
相反,您应该在类内部或方法内部声明它:
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);
}
};
or 要么
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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.