close Alert Dialog without using negative Buttons - java

I created an AlertDialog, which will either refresh the activity (when btnConfirm1 is pressed), or does nothing and simply closes down (when btnDisconfirm1 is pressed). Everything is working apart from btnDisconfirm1. How can I close the dialog?
So apparently AlertDialog does not have a dismiss or cancel method, but is there another way without using negative buttons? The thing is, I created a layout file for this dialog and I don't know how to put a negative button in my xlm-file.
Or should I use a completely different approach apart from AlertDialog? Thanks!
btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder2 = new AlertDialog.Builder(ScoreScreen.this);
View mView2 = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null);
Button btnConfirm1=(Button) mView2.findViewById(R.id.btnConfirm1);
Button btnDisconfirm1=(Button) mView2.findViewById(R.id.btnDisconfirm1);
btnConfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setPlayerScore(0);
player2.setPlayerScore(0);
player3.setPlayerScore(0);
player4.setPlayerScore(0);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
btnDisconfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT DO I PUT HERE???
}
});
mBuilder2.setView(mView2);
AlertDialog dialog = mBuilder2.create();
dialog.show();
}
});

First you should create the AlertDialog with
AlertDialog mDialog = mBuilder2.create();
And secondly you can dismiss the dialog inside the OnClickListener with
mDialog.dismiss();

You can put this method in your Util class. and use callbacks
public interface OnDialogDismiss {
void onPositiveClick();
void onNegativeClick();
}
Modify it as your requirement.
public void showDialogForMultipleCallback(Context context, String title, String message, boolean cancellable, String neutralBbtn, String negativeBtn, String positiveBtn, final OnDialogDismiss onDialogDismiss) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(cancellable);
if (neutralBbtn != null) {
builder1.setNeutralButton(neutralBbtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (negativeBtn != null) {
builder1.setNegativeButton(negativeBtn,
new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (positiveBtn != null) {
builder1.setPositiveButton(positiveBtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onDialogDismiss.onPositiveClick();
}
});
}
alert11 = builder1.create();
alert11.show();
}

Related

The button that I have created does not work. Is there something wrong with my code?

I am building an app in Android studio and basically I want a window to popup when a user clicks the add button. I used the setOnClickListener but when I run the app, nothing happens. Could there possibly something wrong with my code?
Here's my MainActivity code
public class MainActivity extends AppCompatActivity {
Button addBtn;
ListView itemListView;
DatePickerDialog.OnDateSetListener dateSetListener;
String dateString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button)findViewById(R.id.addBtn);
itemListView = (ListView)findViewById(R.id.itemListView);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.activity_popup_window, null);
EditText itemName = (EditText)view.findViewById(R.id.itemName);
Button expirationDateBtn = (Button)view.findViewById(R.id.expirationDateBtn);
builder.setView(view)
.setTitle("Add Item")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (itemName.getText().toString().isEmpty() || dateString == null) {
Toast.makeText(MainActivity.this,
"Item name or expiration date is missing",
Toast.LENGTH_LONG).show();
}
else{
//do action
}
}
});
//when clicked on Expiration Date Btn
//display date on button
AlertDialogBuilder doesn't create and show a new AlertDialog implicitly. It only prepares the dialog before explicitly calling create() (or you can directly call show() if you need to display your dialog in the moment it gets built).
Your code misses the following lines at the end of onClick():
AlertDialog dialog = builder.create();
dialog.show();
or just:
builder.show();

Android: What is the best practice to organize methods to show alert dialog

I am beginner in Android development. Suppose I have some methods to show AlertDialog within an Activity. But each AlertDialog behavior is slightly different. What is the best practice to organize the methods to show AlertDiaolog?
code is like this.
private void showNumberPickerDialog() {
LayoutInflater inflater = this.getLayoutInflater();
View numberPickerDialogView = inflater.inflate(R.layout.number_picker, null);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title for number picker here");
alertDialog.setCancelable(false);
alertDialog.setView(numberPickerDialogView);
final NumberPicker numberPicker = roomSizeNumberDialogView.findViewById(R.id.number_picker);
numberPicker.setMaxValue(10);
numberPicker.setMinValue(0);
numberPicker.setWrapSelectorWheel(false);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Something here
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void showMessageDialog(final boolean isA) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isA) {
doA();
} else {
doB();
}
}
});
alertDialog.show();
}
private void showAlertDialogC() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
final EditText inputEditText = new EditText(this);
inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
innputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
alertDialog.setTitle("Title here");
alertDialog.setCancelable(false);
alertDialog.setView(nameEditText);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do something here
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
Is there a good way to organize the parts like this?
You can also use a customizable dialog if that's what you are looking for.
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_options);
dialog.show();
TextView tvDelete = dialog.findViewById(R.id.tvDelete);
tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Dialog deleteDialog = new Dialog(context);
deleteDialog.setContentView(R.layout.dialog_delete);
deleteDialog.show();
}
});
Treat it just like you would treat an activity. Set onClickListeners on the views for which you want some particular actions. I believe this custom dialog is much more flexible than the AlertDialog
I like to handle my dialog in a separate class, that way you have more control over everything - clickListners, layout design, etc... and you don't have tons of code lines in your activity.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog

Why is my Android snackbar dismissed after clicking its action button?

I have a snackbar that I build with a duration set to Snackbar.LENGTH_INDEFINITE
The snackbar is displayed properly when I call mySnackbar.show();
But as soon as I hit the action button, the snackbar is dismissed.
The dismiss method seems called by the system.
Does anyone know a workaround ?
Here is my code for building my snackbar:
Snackbar mySnackbar = Snackbar.make(mParent, R.string.the_question, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.yes, new View.OnClickListener() {
#Override
public void onClick(View v) {
//My code...
}
})
.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
}
#Override
public void onShown(Snackbar snackbar) {
}
});
Below code is showing the Alert dialog "after" the snackbar is displayed.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
"This is Snackbar", Snackbar.LENGTH_INDEFINITE).
setAction(R.string.yes, new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
}
#Override
public void onShown(Snackbar sb) {
super.onShown(sb);
}
});
snackbar.show();
showAlertDialog(this, "Alert!!", "Alert Dialog", "Yes", "No");
}
The showAlertDialog is simple static method to show the dialog
public static void showAlertDialog(Context context, String title, String message, String posBtnMsg, String negBtnMsg) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(posBtnMsg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
The screen shot of the output for above code is below,
The answer to this question lies in the way Snackbar.setAction(CharSequence text, final View.OnClickListener listener) is implemented
If you pass this method a non empty text or non null listener, the TextView displaying the action's text is set an OnClickListener which calls BaseTransientBottomBar.dispatchDismiss(BaseCallback.DISMISS_EVENT_ACTION) when the action is performed. This causes the Snackbar to be dismissed.
To prevent that, one needs to retrieve the TextView of the Snackbar's action view, and override its OnClickListener with a listener that does not call dispatchDismiss()
Here is the Snackbar.setAction() code for reference
public Snackbar setAction(CharSequence text, final View.OnClickListener listener) {
final SnackbarContentLayout contentLayout = (SnackbarContentLayout) mView.getChildAt(0);
final TextView tv = contentLayout.getActionView();
if (TextUtils.isEmpty(text) || listener == null) {
tv.setVisibility(View.GONE);
tv.setOnClickListener(null);
} else {
tv.setVisibility(View.VISIBLE);
tv.setText(text);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onClick(view);
// Now dismiss the Snackbar
dispatchDismiss(BaseCallback.DISMISS_EVENT_ACTION);
}
});
}
return this;
}

Hide AlertDialog in specific activity

I have one Quote application. When I open the application's MainActivity, if there is new data updated on the server side, one AlertDialog is shown for going to SettingsActivity. It takes some time for appear so if the app is already on SettingsActivity, it is still showing the AlertDialog to go to SettingsActivity.
I want to prevent the AlertDialog from showing in SettingsActivity but continue showing in other activities. My code for AlertDialog is below. How can I do that?
public class UpdatesDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(UpdatesDialogActivity.this);
builder.setTitle("Download New Status");
builder.setMessage("There Are New Status Arrived. Push Download Button From Settings.");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(UpdatesDialogActivity.this, SettingsActivity.class);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
finish();
return false;
}
});
builder.show();
}
// ==============================================================================
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
You can go for an 'instanceof' check and see if the current activity is settings or else.
if(activity instanceof SettingsActivity){
//don;t show dialog
}else{
//show dialog
}
Hope this will help.

Get User Selection in Alert Dialog

I have a button inside a popupwindow that when clicked initializes an alertdialog with a list from which the user can choose from. I'm stuck trying to get the string value of the selected item from the list. I'm trying to get the item and then change the description text on the button to reflect the user's selection.
countryButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String countryResult = countryList.get(which);
//countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
You have to use ArrayAdapter.getItem() method. And if it isn´t just a copy paste mistake, don´t forget the #Override annotation. But what do You mean with "missing reference error"?
countryButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String countryResult = countryAdapter.getItem(which);//use this getItem() method
countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});

Categories