MainActivity报错如何解决,是独立类和接口类监听事件报错,匿名内部类和外部类实现监听事件没错。
Error:(54, 32) 错误: 不兼容的类型: com.example.mook.shiyan.OnClickListener无法转换为android.view.View.OnClickListener
Error:(55, 32) 错误: 不兼容的类型: MainActivity无法转换为OnClickListener
注: 某些消息已经过简化; 请使用 -Xdiags:verbose 重新编译以获得完整输出
2 个错误
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
package com.example.mook.shiyan;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button yesbutton;
private Button bt1;
private Button bt2;
private Button bt3;
private ImageButton bt4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yesbutton=(Button)findViewById(R.id.button);
bt1=(Button)findViewById(R.id.button2);
bt2=(Button)findViewById(R.id.button3);
bt3=(Button)findViewById(R.id.button4);
bt4=(ImageButton)findViewById(R.id.imageButton);
yesbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
System.out.println("我的Button被点击了");
}
});
bt1.setOnClickListener(new MyOnClickListener() {
@Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(MainActivity.this, "bt1被执行", 1).show();
}
});
bt2.setOnClickListener(new MyOnClickListener() {
@Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(MainActivity.this, "bt2被执行", 1).show();
}
});
bt3.setOnClickListener(listener);
bt4.setOnClickListener(this);
}
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
Log.i("tag","独立类的监听事件被触发了");
}
};
public void onClick(View v){
Log.i("tag","第三种方式实现");
}
class MyOnClickListener implements View.OnClickListener{
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onClick(View v){
v.setAlpha(0.5f);
}
}}