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

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;
}

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();

close Alert Dialog without using negative Buttons

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();
}

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();
}
});

Closing Custom Dialog Box

I am Using the following code for my custom dialog box.
Code is here
I am using a new layout by setCustomView Method.That layout contains a 'Ok' button and a 'Cancel' button.
I need to close the dialog box when click on cancel.
buttonCancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("onClick" , "YYYYY");
//up to this comes , here what I can wright
}
});
dialogObject.dismiss();
You can use this method
Why not you create custom dialog from here:
http://developer.android.com/guide/topics/ui/dialogs.html#CustomLayout
Very clearly explained and easy to implement too.
try this :
buttonCancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("onClick" , "YYYYY");
qustomDialogBuilder.dismiss();//this line will close the dialog
}
});
Replace your TestDialogActivity like below,
public class TestDialogActivity extends Activity {
private static final String HALLOWEEN_ORANGE = "#FF7F27";
private AlertDialog alertDialog;
private OnClickListener mShowDialogClickListener = new OnClickListener() {
public void onClick(View v) {
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(
v.getContext())
.setTitle("Set IP Address")
.setTitleColor(HALLOWEEN_ORANGE)
.setDividerColor(HALLOWEEN_ORANGE)
.setMessage("You are now entering the 10th dimension.")
.setCustomView(R.layout.example_ip_address_layout,
v.getContext())
.setIcon(getResources().getDrawable(R.drawable.ic_launcher));
alertDialog=qustomDialogBuilder.create();
qustomDialogBuilder.setAlertDialog(alertDialog);
alertDialog.show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(mShowDialogClickListener);
}
and replace setCustomView of QustomDialogBuilder like below
public QustomDialogBuilder setCustomView(int resId, final Context context) {
View customView = View.inflate(context, resId, null);
((TextView)customView.findViewById(R.id.ip_text)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
((FrameLayout)mDialogView.findViewById(R.id.customPanel)).addView(customView);
return this;
}
finally add below line into your QustomDialogBuilder
private AlertDialog alertDialog;
public void setAlertDialog(AlertDialog alertDialog)
{
this.alertDialog=alertDialog;
}
To close your dialog click on IP Address text.
Using the QustomDialog Source here in your activity class (TestDialogActivity), you can set the "Ok" and "Cancel" button by setting the Negative and Positive button of the dialog like this:
private OnClickListener mShowDialogClickListener =new OnClickListener(){
public void onClick(View v){
QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()).
setTitle("Set IP Address").
setTitleColor(HALLOWEEN_ORANGE).
setDividerColor(HALLOWEEN_ORANGE).
setMessage("You are now entering the 10th dimension.").
setCustomView(R.layout.example_ip_address_layout, v.getContext()).
setIcon(getResources().getDrawable(R.drawable.ic_launcher));
qustomDialogBuilder.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
qustomDialogBuilder.setPositiveButton("Ok", new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
/**
* Do something here...
*/
}
});
qustomDialogBuilder.show();
}
};
And it will look like this:
Hope you'll find this helpful. Thanks!

how to unselect all my checkbox

I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});

Categories