Hi guys I have a custom alert dialog I created. In the builder I set cancelable to false yet it still disappears when I press the back button, any ideas?
This is the code for the dialog:
public final class HemisphereDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View customTitle = inflater.inflate(R.layout.hemisphere_dialog_custom_title, null);
builder.setCustomTitle(customTitle);
String[] entries = new String[2];
entries[0] = getResources().getString(R.string.northern_hemisphere);
entries[1] = getResources().getString(R.string.southern_hemisphere);
builder.setItems(entries, new DialogInterface.OnClickListener() {
//The 'which' argument contains the index position of the selected item
public void onClick(DialogInterface dialog, int which) {
if( which == 0 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(true);
} else if( which == 1 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(false);
}
ToolbarActivity.outfitsFragment.hemisphereSelected();
GlobalVariables.getShared().setHasAskedForHemisphere(true);
}
});
builder.setCancelable(false);
//Create the AlertDialog object and return it
return builder.create();
}
And this is how it's displayed:
new HemisphereDialogFragment().show(getSupportFragmentManager(), "hemisphereDialog");
Another small side question, is there a way to change the text size for the items in the dialog?
You set your alert dialog cancelable to false, but your fragment is still set to cancelable, you need to add setCancelable(false) to your fragment as well.
You should call setCancellable(false) in the Dialog fragment itself not the AlertDialog.Builder.
Related
I try to get dynamically an identifier of some checkbox in a AlertDialog.
But I do not find the right code for this.
Every time I get return 0.
I have a test to get id of alert title ("android:id/alertTitle")
And this works fine. But I'am not able to reach my inflater-ID's
For me it seems like the context is wrong?
AlertDialog.Builder builder = new AlertDialog.Builder(Claim.this);
builder.setView(optionmenu);
final CheckBox[] myCheckBox = new CheckBox[checkedItems.length];
builder.setTitle("Select pages for claim");
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
for(int i=0; i<checkedItems.length; i++) {
String checkboxID = "android:id/optionspage"+i+"CheckBox";
int resID = builder.getContext().getResources().getIdentifier(checkboxID, null, null);
myCheckBox[i] = ((CheckBox) findViewById(resID));
myCheckBox[i].setChecked(checkedItems[i]);
}
What am I doing wrong here? Thanks.
I have implemented form in my dialog, and when positive button is clicked I create new object to ma database. I've created global variable for EditText's but still not work. Where I want get text value from them I always get empty string.
here is code:
EditText name, desc;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
builder.setView(inflater.inflate(R.layout.new_dialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyDbHelper helper = new MyDbHelper (getActivity());
MyObj w = new MyObj ();
w.setName(name.getText().toString(););
w.setDescription(desc.getText().toString());
w.setLevel(1);
long id = helper.createWorkout(w);
Toast.makeText(getActivity(), id+"", Toast.LENGTH_LONG).show();
callback.onPositiveButtonClick();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
callback.onNegativeButtonClick();
}
});
return builder.create();
}
Any ideas please?
I stumbled upon the same issue. You can get the views inflated in the dialog using getDialog() provided by the onClick.
((EditText) getDialog().findViewById(R.id.your_editText_ID)).getText().toString()
In below code, you are inflating new_dialog layout and your name and desc EditTexts belong to this layout.
view = inflater.inflate(R.layout.new_dialog, null);
name = (EditText) view.findViewById(R.id.workout_name);
desc = (EditText) view.findViewById(R.id.workout_description);
But when you are setting the layout of the dialog you are setting new_workout_dialog. your name and desc do not belong to this layout.
builder.setView(inflater.inflate(R.layout.new_workout_dialog, null))
Furthermore, even if you used new_dialog while setting the builders view, name and desc would still be irrelevant. Because you are completely creating a new view inside setView method.
Use the view variable as following:
builder.setView(view, null))
I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}
Possible duplicate here, sorry in that case...
I can't get my head around how to add a custom style to my DialogFragment. At the moment I have a class
public final class SelectFragment extends DialogFragment {
which I call from different parts of my app. E.g from my "CreateInvoice" class like this:
private void showFragment(int selectedIndex) {
SelectFragment fragment = SelectFragment.newInstance(selectedIndex, getOnOptionSelectListener());
fragment.setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog);
fragment.show(getActivity().getSupportFragmentManager(), "");
}
What I want to do is to change the fragment.setStyle to a custom one, for example with my own color scheme as color on the border, background etc.. And I would really appreciate if someone could walk me through it since it's the first time I've worked with fragments. :-)
Thanks!
The way I would do it is to simply write your own layout for your dialog, then load it up when you show the fragment
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View v = inflater.inflate(R.layout.custom_dialog_layout, null, false);
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.save_note, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// do stuff
}
})
.setNegativeButton(R.string.note_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do stuff
}
});
I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.
I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.
So far I have:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.
Thanks
I think you should recreate the Dialog, as it seems the DialogInterface given as a parameter in onClick() doesn't give you an option to stop the closure of the Dialog.
I also have a couple of tips for you:
Try using Activity.onCreateDialog(), Activity.onPrepareDialog() and of course Activity.showDialog(). They make dialog usage much easier (atleast for me), also dialog usage looks more like menu usage. Using these methods, you will also be able to more easilty show the dialog again.
I want to give you a tip. It's not an answer to your question, but doing this in an answer is much more readable.
Instead of holding a reference to an AlertDialog.Builder() object, you can simply do:
new AlertDialog.Builder(this)
.setTitle("Record New Track")
.setMessage("Please Name Your Track:")
//and some more method calls
.create();
//or .show();
Saves you a reference and a lot of typing ;). (almost?) All methods of AlertDialog.Builder return an AlertDialog.Builder object, which you can directly call a method on.
The same goes for Toasts:
Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
I make a new method inside my class that shows the alert and put all the code for creating the alert in that one method. then after calling the Toast I call that method. Say I named that method createAlert(), then I have,
createAlert(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
createAlert();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
}
What you should do is to create a custom xml layout including a textbox and an Ok button instead of using .setPositiveButton.
Then you can add a click listener to your button in order to validate the data and dismiss the dialog.
It should be used in CreateDialog:
protected Dialog onCreateDialog(int id)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (id==EDIT_DIALOG)
{
final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit));
final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack);
final EditText name=(EditText) layout.findViewById(R.id.EditText_Name);
okButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
String textString = trackName.getText().toString();
if (textString != null && textString.trim().length() ==0)
{
Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show();
} else
removeDialog(DIALOG_EDITTRACK);
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Edit text");
AlertDialog submitDialog = builder.create();
return submitDialog;
}
Even though it's an old post, the code below will help somebody. I used a customized layout and extended DialogFragment class.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.Name_of_the_customized_layout, null);
final EditText etxtChamp = view.findViewById(R.id.editText);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Enter a Name")
.setTitle("Mandatory field ex.");
builder.setView(view);
final Button btnOk = view.findViewById(R.id.ok);
final Button btnCancel = view.findViewById(R.id.cancel);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(etxtChamp.getText().toString().isEmpty()){
etxtChamp.setError("Oups! ce champ est obligatoire!");
}else{
//Get the editText content and do whatever you want
String messageEditText = etxtChamp.getText().toString();
dismiss();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
Use This code for displaying Dialog.
public void onClick(DialogInterface dialog, int whichButton) {
String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("please enter valid field")
.setPositiveButton("OK", null).show();
}
This will create a Dialog for you, editText is empty or what are conditions you wants.
//if view is not instantiated,it always returns null for edittext values.
View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v);
final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description);