Created
November 26, 2014 10:00
-
-
Save noties/33a5507d0e2f157faab4 to your computer and use it in GitHub Desktop.
SnackbarManagerImpl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.os.Handler; | |
import android.os.Message; | |
import com.nispok.snackbar.Snackbar; | |
import java.lang.ref.WeakReference; | |
import java.util.HashMap; | |
import java.util.Map; | |
import ru.noties.debug.Debug; | |
/** | |
* Created by Dimitry Ivanov (noties.app@gmail.com) on 26/11/14. | |
*/ | |
public class SnackbarManager { | |
private static volatile SnackbarManager sInstance = null; | |
public static SnackbarManager getInstance() { | |
SnackbarManager localInstance = sInstance; | |
if (localInstance == null) { | |
synchronized (SnackbarManager.class) { | |
localInstance = sInstance; | |
if (localInstance == null) { | |
localInstance = sInstance = new SnackbarManager(); | |
} | |
} | |
} | |
return localInstance; | |
} | |
private final Map<String, WeakReference<Snackbar>> mSnacks; | |
private final Handler mHandler; | |
private SnackbarManager() { | |
mSnacks = new HashMap<>(); | |
mHandler = new SnackHandler(); | |
} | |
public void show(Activity activity, Snackbar snackbar, String tag) { | |
if (tag != null) { | |
final WeakReference<Snackbar> reference = mSnacks.get(tag); | |
final Snackbar currentSnack = reference == null ? null : reference.get(); | |
// if we are still holding a snack instance - then dismiss it | |
if (currentSnack != null) { | |
currentSnack.dismiss(); | |
mSnacks.remove(tag); | |
mHandler.removeMessages(SnackHandler.END, tag); | |
} | |
mSnacks.put(tag, new WeakReference<>(snackbar)); | |
final long duration = snackbar.getDuration(); | |
final Message message = mHandler.obtainMessage(SnackHandler.END, tag); | |
mHandler.sendMessageDelayed(message, duration); | |
} | |
snackbar.show(activity); | |
} | |
private class SnackHandler extends Handler { | |
static final int END = 1; | |
@Override | |
public void handleMessage(Message msg) { | |
final String tag = (String) msg.obj; | |
final boolean result = mSnacks.remove(tag) != null; | |
Debug.i("tag: %s, result: %s", msg.obj, result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment