Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing typeface of Snackbar

I build Snackbar by this code:

Snackbar sb = Snackbar.make(drawer,  "message", Snackbar.LENGTH_LONG)
       .setAction("action", new View.OnClickListener() {
       @Override
       public void onClick(View view) {

       }
});

Now I want to change the typeface of message and action button but can't find any solution, How to do that?

like image 232
user5510211 Avatar asked Nov 04 '15 08:11

user5510211


4 Answers

You can set TypeFace by getting view from Snack bar

TextView tv = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/font_file.ttf");
tv.setTypeface(font);

For AndroidX, use resource ID com.google.android.material.R.id.snackbar_text

like image 162
Ashish Agrawal Avatar answered Oct 16 '22 18:10

Ashish Agrawal


Styling Both the Snackbar Text and Action

You can use the same method to style both the snackbar_text and snackbar_action.

Once you've created a snackbar, you can use the following to get the Views associated with the text and the action and then apply whatever adjustments to the view.

Snackbar snackbar = Snackbar.make( ... )    // Create the Snackbar however you like.

TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );
snackbarActionTextView.setTextSize( 20 );
snackbarActionTextView.setTypeface(snackbarActionTextView.getTypeface(), Typeface.BOLD);

TextView snackbarTextView = (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextSize( 16 );
snackbarTextView.setMaxLines( 3 );

In my example, I've set the Action to be font size 20 and Bold, and the Text to be size 16 and allow up to 3 lines.

like image 15
Joshua Pinter Avatar answered Oct 16 '22 18:10

Joshua Pinter


For AndroidX

android.support.design.R.id.snackbar_text won't be available.

Use com.google.android.material.R.id.snackbar_textinstead.

If you are using kotlin, then I prefer you to use extension function:

fun Snackbar.changeFont()
{
    val tv = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
    val font = Typeface.createFromAsset(context.assets, "your_font.ttf")
    tv.typeface = font
}

and call it like:

mSnakeBar.changeFont()
like image 14
Suraj Vaishnav Avatar answered Oct 16 '22 16:10

Suraj Vaishnav


In addition to this answer: now package to find snackbar's textview by id is

val snackText = snackView.findViewById<TextView>(
                    com.google.android.material.R.id.snackbar_text)
like image 5
STAYER Avatar answered Oct 16 '22 17:10

STAYER