问题描述
下面是我的计划,我收到此错误:
Description Resource Path Location Type
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (welcome) welcome.java /testcalculator/src/com/testcalculator line 31 Java Problem
welcome.java
package com.testcalculator;
public class welcome extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome1);
Button playBtn = (Button) findViewById(R.id.playBtn);
playBtn.setOnItemClickListener();
Button exitBtn = (Button) findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(this);
}
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.playBtn :
i = new Intent(this, testcalculator.class);
startActivity(i);
break;
case R.id.exitBtn :
finish();
break;
}
}
}
现在的问题是,我有我的问题,但仍然我得到错误信息所需的所有导入选项。
The problem is, I have all the required import options in my problem but still I am getting error message.
推荐答案
正在通过你的Activity类为OnClickListener在这一行:
You are passing your Activity class as the OnClickListener in this line:
exitBtn.setOnClickListener(this);
不过,你的类需要显式声明,它正在实施 View.OnCLickListener
接口。改变你的类报关行这样:
However, your class needs to explicitly declare that it is implementing the View.OnCLickListener
interface. Change your class declaration line to this:
public class welcome extends Activity implements OnClickListener
一对夫妇的其他注意事项:
A couple of other things to note:
您写了 playBtn.setOnItemClickListener()
。也许你的意思 playBtn.setOnClickListener(本)
?按钮没有OnItemClickListeners
You wrote playBtn.setOnItemClickListener()
. Perhaps you meant playBtn.setOnClickListener(this)
? Buttons don't have OnItemClickListeners
您还可以设置一个OnClickListener不具有活性的类本身声明一个匿名类实现的接口。像这样的:
You can also set an OnClickListener without having the activity class itself implement the interface by declaring an anonymous class. Like this:
playBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// playBtn code
}
});
exitBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// exitBtn code
}
});
此方法更常用,因为它更具有可读性。通过分离按钮的onClick code,你可以很容易地分辨哪个按钮做什么,而不是把它全部变成一种方法,并具有类本身实现OnClickListener。
This way is used more often because it is more readable. By segregating the button onClick code, you can easily tell which button does what, as opposed to putting it all into one method and having the class itself implement OnClickListener.
这篇关于setOnClickListener没有工作和投掷错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!