Prevent Android activity dialog from closing on outside touch - java

I have an activity that is using the Theme.Dialog style such that it is a floating window over another activity. However, when I click outside the dialog window (on the background activity), the dialog closes. How can I stop this behaviour?

To prevent dialog box from getting dismissed on back key pressed use this
dialog.setCancelable(false);
And to prevent dialog box from getting dismissed on outside touch use this
dialog.setCanceledOnTouchOutside(false);

What you actually have is an Activity (even if it looks like a Dialog), therefore you should call setFinishOnTouchOutside(false) from your activity if you want to keep it open when the background activity is clicked.
EDIT: This only works with android API level 11 or greater

What worked for me was to create DialogFragment an set it to not be cancelable:
dialog.setCancelable(false);

This could help you. It is a way to handle the touch outside event:
How to cancel an Dialog themed like Activity when touched outside the window?
By catching the event and doing nothing, I think you can prevent the closing. But what is strange though, is that the default behavior of your activity dialog should be not to close itself when you touch outside.
(PS: the code uses WindowManager.LayoutParams)

When using dialog as an activity in the onCreate add this
setFinishOnTouchOutside(false);

For higher API 10, the Dialog disappears when on touched outside, whereas in lower than API 11, the Dialog doesn't disappear. For prevent this, you need to do:
In styles.xml: <item name="android:windowCloseOnTouchOutside">false</item>
OR
In onCreate() method, use: this.setFinishOnTouchOutside(false);
Note: for API 10 and lower, this method doesn't have effect, and is not needed.

Setting the dialog cancelable to be false is enough, and either you touch outside of the alert dialog or click the back button will make the alert dialog disappear. So use this one:
setCancelable(false)
And the other function is not necessary anymore:
dialog.setCanceledOnTouchOutside(false);
If you are creating a temporary dialog and wondering there to put this line of code, here is an example:
new AlertDialog.Builder(this)
.setTitle("Trial Version")
.setCancelable(false)
.setMessage("You are using trial version!")
.setIcon(R.drawable.time_left)
.setPositiveButton(android.R.string.yes, null).show();

Alert Dialog is deprecated so use Dialog dialog = new Dialog(this);
For prevent close on outside touch
dialog.setCanceledOnTouchOutside(false);

Use This Code it's Working For me
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setCancelable(false);

Dialog dialog = new Dialog(context)
dialog.setCanceledOnTouchOutside(true);
//use this to dismiss the dialog on outside click of dialog
dialog.setCanceledOnTouchOutside(false);
//use this for not to dismiss the dialog on outside click of dialog.
Watch this link for more details about dialog.
dialog.setCancelable(false);
//used to prevent the dismiss of dialog on backpress of that activity
dialog.setCancelable(true);
//used to dismiss the dialog on onbackpressed of that activity

Simply,
alertDialog.setCancelable(false);
prevent user from click outside of Dialog Box.

I use this in onCreate(), seems to work on any version of Android; tested on 5.0 and 4.4.x, can't test on Gingerbread, Samsung devices (Note 1 running GB) have it this way by default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
setFinishOnTouchOutside(false);
}
else
{
getWindow().clearFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
}
super.onCreate(savedInstanceState);

Use setFinishOnTouchOutside(false) for API > 11 and don't worry because its android's default behavior that activity themed dialog won't get finished on outside touch for API < 11 :) !!Cheerss!!

alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
I guess this will help you.It Worked For me

Here is my solution:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Difficulty Level");
builder.setCancelable(false);

Also is possible to assign different action implementing onCancelListener:
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialogInterface) {
//Your custom logic
}
});

I was facing the same problem. To handle it I set a OntouchListener to the dialog and do nothing inside. But Dialog dismiss when rotating screen too. To fix it I set a variable to tell me if the dialog has normally dismissed. Then I set a OnDismissListener to my dialog and inside I check the variable. If the dialog has dismmiss normally I do nothin, or else I run the dialog again (and setting his state as when dismissing in my case).

builder.setCancelable(false);
public void Mensaje(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("¿Quieres ir a el Menú principal?");
builder.setMessage("Al presionar SI iras a el menú y saldras de la materia.");
builder.setPositiveButton("SI", null);
builder.setNegativeButton("NO", null);
builder.setCancelable(false);
builder.show();
}

In jetpack compose, use dismissOnClickOutside = false property to prevent from closing.
AlertDialog(
title = {
Text("Title")
},
text = {
Text(text = name)
},
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onDismiss ) {
Text("Yes")
}
},
dismissButton = {
TextButton(onClick = onDismiss ) {
Text("Cancel")
}
},
properties = DialogProperties(
dismissOnClickOutside = false
)
)
}

This is the perfect answer to all your questions.... Hope you enjoy coding in Android
new AlertDialog.Builder(this)
.setTitle("Akshat Rastogi Is Great")
.setCancelable(false)
.setMessage("I am the best Android Programmer")
.setPositiveButton("I agree", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();

Related

Dialog Box Appears for half a second and closes automatically

I am trying to create a very simple dialog box. I found the code references from the internet obviously.
My code is this:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
ConsignmentConViewActivity.this);
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to AndroidHive.info");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialogMain = alertDialog.create();
alertDialogMain.show();
The youtube videos and google link that talks about dialog boxes and are similar to the code above. It even works for the people showing the demo on youtube.
But when I run it, the dialog box appears for half a second like I can see it. and then closes automatically. It appears and then its gone.
I have also tried to reboot my system. Nothing works.
Yes because you created it as it shows.
Why are you declaring a new variable as the below code if you already declared alertDialog above?
AlertDialog alertDialogMain = alertDialog.create();
alertDialogMain.show();
This problem is showing because you are declaring a new variable when you have already declared it. Make your code as below I maintained.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
ConsignmentConViewActivity.this);
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to AndroidHive.info");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.create();
alertDialog.show();
OR USE DIRECT WITHOUT DECLARING VARIABLE
new AlertDialog.Builder(this)
.setTitle("Alert Dialog")
.setMessage("Welcome to AndroidHive.info")
//.setIcon(R.drawable.ic_round_warning) // set your dialog icon if you want to show. JJust uncomment.
.setPositiveButton("OK", (dialogInterface, i) -> {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
//dialogInterface.dismiss(); // for dismiss dialogbox
}).create().show();
Let me know if the problem not solved yet.
After grinding on it for almost the whole day, I realized that I have an Intent function right after the dialog box.
The intent function was switching to the next activity.
By the time the dialog would appear, the next code (which was the intent) would run. The activity would change and thats why I was getting that problem.
It works all fine when i removed the intent.
My code (in the question) is all correct and has no problem in it.

Show AlertDialog without hiding ActionBar

I'd like to show an Alert Dialog which does not hide action bar. Is it possible to do it? The code which I tried is:
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("Basemap selection");
builder.setSingleChoiceItems(new String[]{"Create cache", "Use existing file"}, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Some logic here.
}
});
builder.setNegativeButton(R.string.common_cancel, null);
builder.create().show();
It covers the whole screen but I need the action bar to be available while dialog is showing. I know that it might violate some android rules but UX department wants it.
The screenshot is:
If you want to make a non-modal dialog (allowing the user to tap outside the dialog and access the Action Bar while the dialog is visible), there's some information here that may be helpful: timed modeless dialog, specifically the use of dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL); - called after your dialog is visible.
The option is to change the activity to the Dialogue.Its simple process create an activity and goes to manifest file and set the theme of activity as
#android:style/Theme.DeviceDefault.Dialog

how to keep my popup window on orientation change?

I have a popup window in my activity.
Whenever I change the screen orientation to landscape, the popup disappears.
Why is that, and how can I keep the popup visible?
try below code:-
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
Log.i("orientation", "Orientation changed to: Landscape");
else
Log.i("orientation", "Orientation changed to: Portrait");
}
see below link for more info:-
How to keep Popup window opened when orientation changes at run time in Android?
When orientation changes the activity will restart.. So normally the popup window calls again.. In any case if it gone try to call it within onCreate.
Or check the orientation change and take necessary recalls.
if(getResources().getConfiguration().orientation == getResources()
.getConfiguration().ORIENTATION_LANDSCAPE){
// put some flag
}else if(getResources().getConfiguration().orientation != getResources()
.getConfiguration().ORIENTATION_PORTRAIT) {
// change the flag
}
If you put your code fragments may I can help you
You need to use managed Dialogs. Rather than
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.rule_edit_choose_action));
builder.setAdapter(new ArrayAdapter(this, R.array.dummyValues), null);
builder.show();
you should use something like
myActivity.showDialog(0);
and then implement onCreateDialog() in your Activity. Your activity will then manage the dialog and re-show it when you re-orientate and it's closed. If you need to change your dialog every time it is shown, implement onPrepareDialog() also - the Activity will give you access to the Dialog just before it is shown so you can update it (with a custom message, for instance).
There's lots of info here:
http://developer.android.com/guide/topics/ui/dialogs.html
As #Ciril said, your issue is that your Activity is restarted when you re-orientate. You could always fix your activity orientation to portrait or landscape if that is suitable for your app. That would prevent it from restarting.
most likely you use AlertDialog for your popups, something along the lines of:
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.popup_title);
builder.setMessage(R.string.popup_message);
builder.setPositiveButton(R.string.yes, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
});
builder.show();
this is bad, because your Activity has no idea there's a popup dialog, and when you change screen orientation, the Activity is restarted with the new parameters, and your popup is gone.
to avoid this you'd better use ShowDialog() to display your popups. to make it work, you need to override onCreateDialog() :
// Called to create a dialog to be shown.
#Override
protected Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case NEW_DIALOG :
return new AlertDialog.Builder(this)
.setTitle(R.string.popup_title)
.setMessage(R.string.popup_message)
.setPositiveButton(android.R.string.ok, null)
.create();
default:
return null;
}
}
then you'd better override onPrepareDialog() (this is not required, actually):
// If a dialog has already been created, this is called
// to reset the dialog before showing it a 2nd time. Optional.
#Override
protected void onPrepareDialog(int id, Dialog dialog, final Bundle bundle) {
AlertDialog dlg = (AlertDialog) dialog;
switch (id) {
case NEW_DIALOG :
dlg.SetTitle("popup title");
// and maybe something else
}
}
after all preparations you may call ShowDialog(NEW_DIALOG) and you Activity will remember it has a popup laid over on the top, and will recreate it after the orientation change.

Waiting for a response from AlertDialog or Theme.Dialog Activity with onBackPressed()

I have looked at quite a few posts on here and haven't been able to get anything to work. I am trying to have either an AlertDialog or an Activity class (set to a Theme.Dialog style) prompt users to see if they want to exit a side Activity and go back to the Home activity. Everything I have tried just doesn't seem to work.
[NOTE: All of the following examples were tried as the first lines in...]
#Override public void onBackPressed(){}
I have tried -
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
which closes both the current Activity and the Home menu Activity (the next Activity in the stack), while -
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Session.closing = true;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Session.closing = false;
}
});
AlertDialog alert = builder.create();
alert.show();
closes the current Activity and creates a pop-up over the Home activity. This is the outcome of most of the other things I have tried, like...
super.onBackPressed();
startActivity(new Intent(this, CloseActivityView.class));
Are there any tricks to getting onBackPressed from dumping your current child Activity?
First of all, don't call super.onBackPressed(); - this will call finish() and your current activity will be removed.
Secondly, this:
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
creates an intent that launches the Home screen. (See the Intent docs)
What you could do is put something like this in your onBackPressed override:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(this, HomeActivity.class));
finish();
}
})
.setNegativeButton("No", null); // I think passing null here is OK.
AlertDialog alert = builder.create();
alert.show();
Then specify your HomeActivity as launchMode="singleTask" in your manifest, as detailed in the Tasks and Back Stack docs. You could do the same thing by specifying the FLAG_ACTIVITY_NEW_TASK flag on the Intent for navigating to your HomeActivity.
If you want to show a confirmation dialog on back button press then override the onBackPressed and show the AlertDialog. If user confirms then call dialog.dismiss() to dismiss the dialog and then if you want to exit the app and go to the home screen then finish this activity and start the homescreen intent and the code you have tried for this is right. or if you want to go back to an activity within your app then you can start that activity with FLAG_ACTIVITY_CLEAR_TOP. Don't call super.onBackPressed() in your overriden version unless you want to finish the current Activity.
Okay. Three things to say:
if your home activity contents are not changed after navigating away from it, and doing some operations, then, i recommend that when you are navigating awway from homw screen, don't call finish(). Let the home screen be in the activity stack. So when the child activity has to navigate back to home activity, it just needs to finish its own activity, and Home screen will appear after that.
Your code is somewhat perfect. All you have to do is finish the activity when yes button is pressed on AlertDialog
And on Homescreen, inside onBackPressed() or whatever you prefer, just show the AlertDialog (that you have shown above), and you can code for Yes and No buttons

What is wrong with extending AlertDialog also Why no automatic IME in EditText in the dialog

I've got this dialog (I'm simplifying my use case):
class EditShoppingListDialog extends AlertDialog {
public EditShoppingListDialog(Context context) {
super(context/*, R.style.AppCustomDialog*/);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_addshoppinglist);
setTitle("Mike Testing");
}
}
I create and use this subclassed AlertDialog outside of the OnCreateDialog method (in the onContextItemSelected of my Activity) like this:
AlertDialog dialog = new EditShoppingListDialog(this);
dialog.show();
Now, I've been working with this code base for over a month now and never saw any problems, which lead me to wonder why they recommend using AlertDialog.Builder for creating custom dialogs also.
When I deployed my app to a real device, I immediately started to see problems. The most blocking of them is that I cannot get the soft keyboard (IME?) to show up even when I click on an EditText field in the AlertDialog.
Here's the best part; If I say:
class EditShoppingListDialog extends Dialog {
...
}
The IME appears appears automatically if I click in an EditText in the dialog. I found this thread but the accepted solution does not work with AlertDialog.
However, I found doing this on the OnCreate of my derived AlertDialog helps show the IME, but it goes behind the dialog and I can't interact with it:
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,0);
I'm really sorry for the lost post, but I've spent more than 5 hours on this and would be very grateful for some help. The reason I insist on extending an AlertDialog is because I need a dialog without a title bar and it says in the Android Dialog documentation that I cannot have a Dialog without a title bar.
It is easy to set a dialog without title.
create a style as below,
<style name="no_title_dialog" parent="#android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>
initial dialog with
Dialog notitleDialog = new Dialog(this, R.style.no_title_dialog);
the dialog should appear with no title
Having an AlertDialog without a title bar is not magic at all:
AlertDialog.Builder builder;
AlertDialog alertDialog;
TextView v = new TextView(this);
v.setText("Should have no Bar...");
builder = new AlertDialog.Builder(this);
builder.setView(v);
alertDialog = builder.create();
alertDialog.show();
This looks like this:
(No, this is not a Toast!). If this is not what you wanted, you should be more explicit on what you mean by "I need a dialog without a title bar".

Categories

Resources