0

Let's just say I want to create a class that holds all my fonts taken from the assets folder, is it possible?

It's not letting me access the getAssets() without importing android.app.activity.

Utility Class

import android.graphics.Typeface;

public class TypeFontAssets //possibly missing an extends?
{
    public static Typeface cs = Typeface.createFromAssets(getAssets(), "fonts/ComicSans.ttf");
    public static Typeface bh = Typeface.createFromAssets(getAssets(), "fonts/BradleyHand.ttf");
    public static Typeface co = Typeface.createFromAssets(getAssets(), "fonts/Courier.ttf");
}

Main Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //this class for ALL the fonts
        TypeFaceAssets tfa = new TypeFaceAssets();

        TextView userName = (TextView)findViewById(R.id.userNameView);

        //trying to get comic sans from the tfa object
        userName.setTypeface(tfa.cs);
    }
}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
fenrirAB
  • 45
  • 7

1 Answers1

0

It should be possible with some modifications. In this case, since you need to use getAssets(), the class must have a constructor which accepts an object which has that method: Context or Resources.

Here is an example using Context.

public class TypeFontAssets {
    public static Typeface cs;
    public static Typeface bh;
    public static Typeface co;

    public TypeFontAssets(Context context) {
        cs = Typeface.createFromAsset(context.getAssets(),
                "fonts/ComicSans.ttf");
        bh = Typeface.createFromAsset(context.getAssets(),
                "fonts/BradleyHand.ttf");
        co = Typeface.createFromAsset(context.getAssets(),
                "fonts/Courier.ttf");
    }
}

Then in your activity,

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //this class for ALL the fonts
        TypeFaceAssets tfa = new TypeFaceAssets(this); // Activity has Context

        TextView userName = (TextView)findViewById(R.id.userNameView);

        //trying to get comic sans from the tfa object
        userName.setTypeface(tfa.cs);
    }
}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
  • PERFECT that exactly what i needed. OF COURSE, i need to pass a context in order to access the getAssets() of the current project.. I came pretty close. THANK YOU [link]http://Andrew.T.You.Are.Mighty.aninote.com – fenrirAB Aug 08 '14 at 01:42