I\'m having trouble closing my alert dialog. I am using a layout inflator to make the dialog, so I\'m not sure how I would go about closing the thing after I\'m done with it
AlertDialog.Builder dialog = new AlertDialog.Builder(AddData.this);
DialogInterface dia = new DialogInterface();
//Create a custom layout for the dialog box
LayoutInflater inflater = (LayoutInflater)AddData.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.add_rep_1_set, parent, false);
TextView title = (TextView)layout.findViewById(R.id.rep_1_title);
Button add_item = (Button)layout.findViewById(R.id.add_button);
title.setText(workout_items[position]);
dialog.setView(layout);
AlertDialog alertDialog = dialog.create();
add_item.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
alertDialog.dismiss();
}
});
alertDialog.show();
You need to implement DialogInterface.OnClickListener rather than View.OnClickListener. then dialog.dismiss() will be available.
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.dismiss();
}
}
You get error, Try this code
dialog.setView(layout);
final AlertDialog alertDialog = dialog.create();
add_item.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v)
{
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog.show();
Try dialog.cancel(); in your onclick listener. It should work.
use this code in your class:
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
((Button) dialog.findViewById(R.id.button))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
and create custom.xml, then paste this code inside it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Ok "/>
</RelativeLayout>
source: https://www.mkyong.com/android/android-custom-dialog-example/
and if you do not like above code, so see below link: http://thedeveloperworldisyours.com/android/prevent-alertdialog-closing-button-clicked/
Try this:
btn_go_anyway.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
getDialog().dismiss();
}
});