I'm a beginner in java and I have a question for you do you know how I can create the button of exit? This button can ask me before I close the application "Do you want to close this application? or "Are you sure to close it?" I need to do it for my project and I need help. Pls send me some code.
Your question is very broad, however, an AlertDialog is what you are looking for, this is the implementation:
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) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
1.- Search how create a dialog on Android.
Link -> https://developer.android.com/guide/topics/ui/dialogs?hl=es-419
2.- In your view put a back button with onClickListener, insert showDialog created inside.
3.- Implement the override onBackPressed method, insert showDialogCreated inside.
Example onBackPressed
public void onBackPressed() {
var dialog = CustomDialog.newInstance();
dialog.setCancelable(false);
dialog.show(this.getSupportFragmentManager(), "TAG");
dialog.setOnClickListener((whichViewID, tag, args) => {
// Your Logic
// If is pressed positive button call super.onBackPressed else dialog.dismiss()
});
}
I almost finished building an app using android studio. However, I noticed some problems in the testing process.
Here is a brief summary of what I'm doing:
When you click 'button', a popup message appears.
The popup message has two buttons.
Pressing the first button only ends the popup message.
When you press the second button, the current popup message is terminated and additional popup messages appear.
The second popup message has a button and an 'EditText' area for entering the email address.
When you click the button, the popup message ends with performing the Javascript function using the email address entered in the EditText area.
First of all, clicking on the two buttons and entering an email address works normally. But when I do this again for the second time, the app is terminating unexpectedly. I think the 'Builder' part I used to implement the popup message is incorrectly nested, but I can not figure out which part is the problem.
Each pop-up message is implemented using 'Builder' as shown below.
final AlertDialog.Builder builder; //for first popup message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);}
else {
builder = new AlertDialog.Builder(context);}
final AlertDialog.Builder builder2; //for second popup message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder2 = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);}
else {
builder2 = new AlertDialog.Builder(context);}
Now the full popup message implementation code. Sorry for the difficulty of reading the code.
button_makingpopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (User.getInstance() != null) {
builder.setCancelable(false) //first popup setting
.setMessage("Do you want to email the measurement data??")
.setPositiveButton("Save and Send", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); //first popup disappear
builder2.setCancelable(false) //second popup setting
.setMessage("Enter your email address below.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String email_popup = input.getText().toString();
WebView view2 = new WebView(context);
view2.getSettings().setJavaScriptEnabled(true);
view2.getSettings().setDomStorageEnabled(true);
view2.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() { //some javascript function})()");
}
});
dialog.cancel(); //second popup disappear
}
});
AlertDialog alert_send = builder2.create();
alert_send.show(); //second popup appear
}
})
.setNegativeButton("Save only", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); //first popup disappear
}
});
AlertDialog alert = builder.create();
alert.show(); //first popup appear
}
else
//Non-question parts
I would appreciate your advice.
environment: android studio 2.3.3
error message "java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."
I solved this problem by handling the view.
I refer to this. #kasgoku
Thank you also for those who gave me advice by the comment.
So I'm trying to get my application to show an editable text-field in a dialog. Once you've entered your desired text, you can hit 'OK' to use that text to go to the next view and do something based on that text.
So this is what my code looks like.
public void onClick(View v){
final EditText input = new EditText(MainActivity.this);
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("New Query");
alertDialog.setView(input);
alertDialog.setPositiveButton("Fire Query!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
TableView.putExtra("query", input.getText());
startActivity(TableView);
}
});
alertDialog.show();
}
However, the compiler is telling me that it can't resolve setPositiveButton() and in fact when I look look in the code-complete box, it indeed does not show even though it is listed for the builder on the Android documentation
Any ideas? I should mention that everything but the setPositiveButton is working. I just can't do anything with a dialog with a title and an editText field.
You are not calling it on the builder. Move the create() call to later on (and change the type to the Builder).
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
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();