Javi Javi - 3 days ago 7
Android Question

Place snackbar in a Utility class

I am using this method quite a lot to display snackbar messages with the colors used in the app. For this reason I wanted to make the method static and place it in a final class of utilities, so I can use it all over the place and no repeat it everytime.

However, this has the problem that

findViewById
and
getResources().getColor
etc.. need an activity to "live in" and cannot be static either.

Any elegant way to do this? I have been looking in the other posts but none of them did quite reflect this issue.
Thanks!!

protected void displaySnackbar (String s)
{
Snackbar snack = Snackbar.make(findViewById(android.R.id.content), s, Snackbar.LENGTH_LONG);
View sbview = snack.getView();
sbview.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
TextView textView = (TextView) sbview.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(getResources().getColor(R.color.primary_light));
snack.show();
}

Answer

Thanks everyone for your inspiration.. this code works now:

    protected static void sacaSnackbar (Context context, View view, String s)
{
    Snackbar snack = Snackbar.make(view, s, Snackbar.LENGTH_LONG);
    View sbview = snack.getView();
    sbview.setBackgroundColor(ContextCompat.getColor(contexto, R.color.colorAccent));
    TextView textView = (TextView) sbview.findViewById(android.support.design.R.id.snackbar_text);
    textView.setTextColor(ContextCompat.getColor(context, R.color.primary_light));
    snack.show();
}
Comments