I use a snackbar to notify the users of my app that they aren't connected to the internet. I added a "retry" action to the snackbar which re-checks the connection. I want the snackbar to stay displayed until I dismiss it myself (when an internet connection is found), but I can't get this to work. Whenever I click on the action, the snackbar dismisses.
I've set the duration to indefinite and the snackbar does stay open indefinitely but it dismisses when I click on the action.
I've read online that dismissing the snackbar automatically after clicking on the action hasn't always been the default behavior.
edit:
I feel like my question might be badly phrased. I have a snackbar with an action but I don't want the snackbar to close when the action is executed, which it automatically does atm.
You can override the OnClickListener set for the button. First make the snackbar with and set the action with some dummy listener
Snackbar snackbar = Snackbar.make(view,"TXT",Snackbar.LENGTH_LONG).setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View v) { }
});
And then find the button and set your listner
snackbar.show();
ViewGroup group = (ViewGroup) snackbar.getView();
for(int i=0; i< group.getChildCount();i++){
View v = group.getChildAt(i);
if(v instanceof Button){
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
YOUR_ACTION();
}
});
}
}
You can try this
final Snackbar snackbar = Snackbar.make("your view".getRootView(), "Annotations", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("your action", new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
snackbar.show();
}
}, 1);
}
});
snackbar.show();
After the action is clicked, snackbar will close automatically but with some delay, so if you call snackbar.show();
directly in the OnClickListener
, the snack bar will not show. Therefore, to make it show always, give it some delay before showing it. (surprisingly, a one millisecond delay is enough)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With