Why I can not set onClickListener for a button in a dialog view?
I have a custom dialog which described below.
My Custom Dialog layout (*my_dialog.xml*) which only contain a "dismiss" button:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
>
<Button
android:id="@+id/dismiss_btn"
android:layout_width="100dip"
android:layout_height="30dip"
android:layout_centerHorizontal="true"
android:text="Dismiss me"
android:textSize="8dip"
android:textColor="#ffffff"
/>
</RelativeLayout>
my dialog view class:
public class MyDialog extends Dialog{
public MyDialog(Context context){
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.my_dialog);
Button dismissMeBtn = (Button)findViewById(R.id.dismiss_btn);
/** ERROR Message when set onClickListener below (throw by eclipse editor)**/
// The method setOnClickListener(View.OnClickListener) in the
// type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})
dismissMeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyDialog.this.dismiss();
}
});
getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
}
As the code indicated above, I have a "*dismiss_btn*" button on the dialog, I would like to dismiss the dialog when the dismiss button is pressed, but I got an error in my code when setOnClickListener for the dismiss button (as indicated in the code).
Error message (error throw by eclipse editor):
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickLis开发者_高级运维tener(){})
Why I got the error? Why I can not set onClickListener for a button in a dialog view?
As eclipse thinks it is DialogInterface onClickListener but you need a View onClickListener so it will be
dismissMeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyDialog.this.dismiss();
}
});
That is because you are in the context of DialogInterface
and it has OnClickListener
interface on its own.
Your code should be:
dismissMeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyDialog.this.dismiss();
}
});
It seems you have a problem with your imports.
When you try to create a new OnClickListener, you are invoking the constructor of DialogInterface.OnClickListener, which is not the needed OnClickListener for a Button (probably due to an import android.content.DialogInterface.OnClickListener
)
Try to use new View.OnclickListener(){ ... }
or replace the import by import android.view.View.OnClickListener
and it should be alritght.
精彩评论