Search code examples
androidandroid-layoutandroid-support-libraryandroid-snackbarandroid-downloadable-fonts

Use downloadable font as custom Snackbar typeface


Was testing out the new feature with Downloadable fonts for Android using the support library.

Got it working in the whole app on my text views and custom dialogs, but when trying to use it as a custom typeface in a Snackbar it crashed the app. My usage were like this in a dialog OnClick.

Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_confirm_removal_or_wait, Snackbar.LENGTH_LONG)
                                    .setAction(R.string.snackbar_delete, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            String quote = quotes.get(position).quote;
                                            deleteEntry(quote);
                                            quotes.remove(position);
                                            adapter.notifyDataSetChanged();
                                            Snackbar.make(findViewById(android.R.id.content), R.string.snackbar_deleted, Snackbar.LENGTH_SHORT)
                                                    .setDuration(1000)
                                                    .show();
                                        }
                                    })
                                    .setDuration(8500)
                                    .setActionTextColor(ContextCompat.getColor(QuoteActivity2.this, R.color.snackbar_varning_red));
                            TextView textView = (mSnackbar.getView()).findViewById(android.support.design.R.id.snackbar_text);
                            Typeface typeface = ResourcesCompat.getFont(QuoteActivity2.this, R.font.roboto_slab);
                            textView.setTypeface(typeface);
                            snackbar.show();

My logcat gives the following output on the specific crash

E/AndroidRuntime(24199): java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.BaseTransientBottomBar.getView()' on a null object reference

Any thoughts on how to solve it or use the downloadable font as a custom typeface with snackbars?


Solution

  • It looks like you're accessing a field (mSnackbar) in this line:

    TextView textView = (mSnackbar.getView()).findViewById(android.support.design.R.id.snackbar_text);
    

    But you're just assigning the Snackbar to a local variable. Possibly that's the problem?