Android Studio - Set custom fonts with asset manager in fragment

kev picture kev · Jul 26, 2013 · Viewed 7.9k times · Source

I'm rewriting a project of mine to incorporate fragments for use on tablets. I also decided to start using Android Studio with the conversion. Pretty straight forward but I've run into an issue on the pretty simple task of setting a custom font.

I started with these: Custom fonts in android and List of files in assets folder and its subfolders and this Set custom font for Android fragments

In Eclipse my class extended Activity and I did the following in the OnCreate with no problems.(Having a directory and file "assets/FUT_R.ttf")

TextView tv=(TextView)findViewById(R.id.someTextView);
Typeface font = Typeface.createFromAsset(getAssets(), "FUT_R.ttf"); 
tv.setTypeface(font);

now trying to convert this Activity to an ActionBarActivity (fragment with V7 support library) and I've changed the above code to this. (where view is the inflated layout with one Framelayout for phones)

TextView tv=(TextView) view.findViewById(R.id.someTextView);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "FUT_R.ttf"); 
tv.setTypeface(font);

and it crashes at run time with the lovely java.lang.RuntimeException: native typeface cannot be madeeven though i created and 'assets' directory on my new project with FUT_R.ttf in its root.

To confirm the asset manager I tried this code:

String[] f = null;
                try {
                    f = getActivity().getAssets().list("");
                }
                catch (IOException e){
                    e.printStackTrace();
                }
                for(String f1:f){
                    Log.i("names",f1);
                }

And got the following output:

07-26 07:40:40.134    2114-2114/com.myapp I/names: images
07-26 07:40:40.134    2114-2114/com.myapp I/names: sounds
07-26 07:40:40.134    2114-2114/com.myapp I/names: webkit

I'm confused because no where in my 'assets' directory or project do I have these files and/or directories. Obviously the error is the system can't find my font file. WHAT AM I DOING WRONG? Any direction would be greatly appreciated, I've wasted far too much time on this stupid problem.

Thanks!

Answer

kev picture kev · Jul 27, 2013

I finally stumbled upon this: Load a simple text file in Android Studio

which points out the assets folder in Android Studio has apparently been changed. Instead of its normal location in the root app folder (same level as libs, src, ect) it needs to be created under yourapp/src/main/assets. Hopefully this helps someone else. I wasted a lot of time on it!