-1

I've 2 classes the 1st one called Font.java and it has the following code

   package com.example.font;

    package com.example.font;

    import android.content.Context;
    import android.graphics.Typeface;

    public final class Font {
        static Context context;

        // Font path
        static  String fontPath = "fonts/font.ttf";
        // Loading Font Face
        static Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
    }

and the second class is an activity and it has the following

        package com.example.font;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    public class AndroidExternalFontsActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // text view label
            TextView txtGhost = (TextView) findViewById(R.id.ghost);


            // Applying font
            txtGhost.setTypeface(Font.tf);
        }
    }

I would like to set the font which is in Font.java class to to the TextView in the Activity Class.

i tried the above code but it's not working how can i do that ?

thanks.

user3707644
  • 137
  • 3
  • 11

1 Answers1

0

Your Font class is wrong. Your context variable is never assigned, so at

context.getAssets()

you will have a NullPointerException.

Also, please consider never use static references to contexts, since is a well documented memory leak source, as you can check, for example, here

I suggest you to modify your Font class to something similar to:

package com.example.font;

    package com.example.font;

    import android.content.Context;
    import android.graphics.Typeface;

    public final class Font {
        private static final String fontPath = "fonts/font.ttf";

        public Typeface getFont(Context context) {
            return Typeface.createFromAsset(context.getAssets(), fontPath);

        }
    }

And your activity will be like:

public class AndroidExternalFontsActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // text view label
        TextView txtGhost = (TextView) findViewById(R.id.ghost);


        // Applying font
        txtGhost.setTypeface(Font.getFont(this));
    }
}

Also, maybe this answer can be helpful for you.

Community
  • 1
  • 1
Guillermo Merino
  • 3,197
  • 2
  • 17
  • 34