在 Android 開發中,初學者常遇到 setOnClickListener 編譯錯誤。錯誤訊息通常如下:
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity.mClick)
The type MainActivity.mClick must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int)
這通常發生在自定義類別實作 OnClickListener 介面時,卻誤導入錯誤的介面或方法簽名不符。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.shishi);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new mClick());
}
class mClick implements OnClickListener {
public void onClick(View v) {
MainActivity.this.setTitle("改變標題");
txt.setText(R.string.Str1);
}
}
android.view.View.OnClickListener,而非 DialogInterface.OnClickListener。strings.xml 中需定義 R.string.Str1 對應的字串資源。View.OnClickListener 僅需實作 onClick(View v) 方法,而 DialogInterface.OnClickListener 則要求 onClick(DialogInterface dialog, int which)。兩者簽名不同,不可混用。建議使用匿名內部類別或 Lambda 表達式簡化程式碼,減少此類錯誤。