java - NullPointerException when trying to apply custom font to a button -


i declared

public button testbutton; public typeface font; 

in mainactivity.java.

then, in onwindowfocuschanged() inside mainactivity, put in

testbutton = (button)findviewbyid(r.id.testbutton); font=typeface.createfromasset(getassets(), "condensed.ttf"); testbutton.settypeface(font); 

and there's error happening:

08-16 16:33:40.078 27339 27339 e androidruntime: java.lang.nullpointerexception: attempt invoke virtual method 'void android.widget.button.settypeface(android.graphics.typeface)' on null object reference 

but button isn't null, because i'm using onclicklistener on displays toast when clicking button (but in oncreate method)

what doing wrong? works many others, , couldn't me.

edit:

apparently had initialize button variables inside oncreate(), if want same textview, have initialize textview variable inside onwindowsfocuschanged(). information people having same problem in future.

i think should verify font path condensed.ttf file.

sometimes need reuse typeface can make or can create customview:

1-create assets directory in main folder, create folder (fonts directory) assets.

src -- > main -- > assets -- > fonts(optional)

2-create class fonts example.

public class customfonts {  //beware if use other folder assets (/fonts/condensed.ttf).  private final static string condensed_font = "condensed.ttf";  public static typeface typefacecondensed(context context) { return typeface.createfromasset(context.getresources().getassets(), condensed_font);     }  } 

3-apply font

yourview.settypeface(customfonts.typefacecondensed(your_context)); 

in case

testbutton.settypeface(customfonts.typefacecondensed(this)); 

i hope helps!


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

Python Error - TypeError: input expected at most 1 arguments, got 3 -

dns - How To Use Custom Nameserver On Free Cloudflare? -