2014-01-12 92 views
1

我試圖做一個客戶對話框,但我收到錯誤時,我打電話OnClickListener和它通過OnClickListener()類作爲參數。該錯誤是試圖設置一個按鈕的OnClickListner

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new OnClickListener(){})

也是它說的錯誤消息類型來看,它不應該是Button,會是這樣的問題?

代碼

// error message on line below 
Button dialogButton = (Button) dialog.findViewById(R.id.action_settings); 

// if button is clicked, close the custom dialog 
dialogButton.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     dialog.dismiss(); 
    } 
}); 
+0

你能證明你的進口 – Raghunandan

+0

我要猜你使用的錯誤的'進口' –

回答

2

我想你有一個錯誤的進口

確保已

import android.view.View.OnClickListener; 

而且你說

but I'm getting errors when I call setOnClickListener and itpass in a OnClickListener() class as the parameter. 

您需要實現OnClickListener接口。你使用一個匿名的內部類。

你可以做如下

dialogButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        dialog.dismiss(); 
     } 
}); 

例子:

http://androidexample.com/Custom_Dialog_-_Android_Example/index.php?view=article_discription&aid=88&aaid=111

+0

@DavidMays它的一個自定義對話框的按鈕。所以它是正確的 – Raghunandan

+0

@DavidMays http://stackoverflow.com/questions/5417461/how-to-configure-custom-button-in-dialog和這個http://androidexample.com/Custom_Dialog_-_Android_Example/index.php?視圖= article_discription&援助= 88&AAID = 111 – Raghunandan

0

要考慮到的,而不是實現在活動的onClick方法,你可以使用android:onclick屬性上定義按鈕的xml佈局。

<Button 
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:text="@string/self_destruct" 
android:onClick="doSomething" /> 

然後實現在活動的方法DoSomething的:

public void doSomething(View view) { 
// Kabloey 
} 

有關詳細信息:

Button description in Api reference