简体   繁体   中英

Create font class in Android Studio and use it

I want create fonts class and I use it

public class Fonts extends Activity{


public static Typeface typeface;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/dn.ttf");



}

}

and use it for example

      Typeface typeface = Fonts.typeface;

    Button btn_open = (Button)findViewById(R.id.bt_open);
    btn_open.setTypeface(typeface);

but it dosen't change !

in manifests.xml Fonts.java is launcher activity

What do I do ? Thanks

This happens because you are hiding your static variable declaring it again in your onCreate() method. You need to remove the declaration:

public class Fonts extends Activity {
    public static Typeface typeface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Remove the "Typeface" declaration.
        typeface = Typeface.createFromAsset(getAssets(), "fonts/dn.ttf");
    }
}

Personal advice : avoid using a static variable to access to your Typeface . Create a method in which you pass the Context from outside to get the Typeface or initialize it in your Application for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM