1

I want to setup the font in my app.

In the IOS, By using the option 'Fonts provided by application' in the plist, I can setup the fonts in the App.

but I can't find the way to setup in the Android.

I don't want to apply whole application, but want to apply some of Activities what I want.

Is there any option to setup font in Android?? Thanks. (From now on, I used 'WebFont' in the webview. but What I want is not a webFont but 'Setup the font')

Thanks.

Adrian
  • 301
  • 4
  • 15

7 Answers7

0

Create a application class Like This :

public class YourApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        TypeFaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/calibiri.ttf");
    }
}

Create Customer TypeFace Class:

public class TypeFaceUtil {
   public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

        final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Map<String, Typeface> newMap = new HashMap<String, Typeface>();
            newMap.put("serif", customFontTypeface);
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
                defaultFontTypefaceField.setAccessible(true);
                defaultFontTypefaceField.set(null, customFontTypeface);
            } catch (Exception e) {
                Log.e(TypeFaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
            }
        }
    }
}

And Atlast download ttf font and place that in asset folder and finally declare your application class in manifest if you have any doubts please ask

M.Yogeshwaran
  • 1,419
  • 4
  • 22
  • 48
0

In assets folder create a new folder with name "font" and then add there your font .ttf file. In code you can later use and change your view fonts in any activity you want like this:

Typeface robotoBold = Typeface.createFromAsset(getAssets(), "font/roboto_bold.ttf");
textView.setTypeface(robotoBold);
BVantur
  • 1,182
  • 16
  • 11
0

1.Add fonts folder in assets

2.add you required font(font_name.ttf) file in fonts folder.

3.in java code add this,

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/font_name.ttf"); textview.setTypeface(typeface);

rushi
  • 277
  • 2
  • 8
  • Is it possible in the webview??? I want to use the font in the webview by using 'font-family'.. – Adrian Sep 13 '16 at 06:36
  • for webview,here answer is: http://stackoverflow.com/questions/3900658/how-to-change-font-face-of-webview-in-android – rushi Sep 13 '16 at 06:42
  • Hm... but It is the webFont.. I want to setup the font not the webFont. As I know @font-face is for webfont... – Adrian Sep 13 '16 at 06:49
0

Hey Adrian checkout this links for setting font in android Webview

http://velmuruganandroidcoding.blogspot.in/2014/08/set-typeface-for-webview-in-android.html

How to change font face of Webview in Android?

Community
  • 1
  • 1
Piyush Patel
  • 371
  • 1
  • 5
  • 13
  • Haha Thanks. but It is not the right way. cuz It is based on the 'webFont' like '@font-face...'. but what i want is not the webfont but setup the font like 'Fonts provided by application' of IOS – Adrian Sep 13 '16 at 06:41
  • in android there is no such way as iOS provided you need to code for that to set custom font in android – Piyush Patel Sep 13 '16 at 06:43
  • so, In the Android, Do I have to use web-font in the webview not the setup font?? – Adrian Sep 13 '16 at 06:47
  • Not actually, if your webpage have font style and supported fonts then it will display. otherwise it will display default font style – Piyush Patel Sep 13 '16 at 06:56
0

LargeText.java

public class LargeText extends TextView {

 public LargeText(Context context) {
    super(context);

    init();
}

private void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "your_font_file_name.ttf");
    setTypeface(tf);
}

public LargeText(Context context, AttributeSet attrs) {
    super(context, attrs);

    init();
}

public LargeText(Context context, AttributeSet attrs, int defStyleAttr)    

 {
    super(context, attrs, defStyleAttr);

    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public LargeText(Context context, AttributeSet attrs, int    
 defStyleAttr, 
  int defStyleRes) {


       super(context, attrs, defStyleAttr, defStyleRes);
     init();
}

 }

Use this class as follow in you xml file:(for TextView this is an example you can do it for other components too)

   <com.example.demo.LargeText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
Harshad07
  • 608
  • 7
  • 23
0

There is a various way to setup the custom font in android. But It's not simple like iOS, we have to do some stuff. In my experience, an efficient way to do it is create a CustomTextView, the code look like:

public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(attrs);
}

public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);

}

public CustomTextView(Context context) {
    super(context);
    init(null);
}

private void init(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
        String fontName = a.getString(R.styleable.FontTextView_fontName);
        if (fontName != null) {
            Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "opensans/" + fontName);
            setTypeface(myTypeface);
        }
        a.recycle();
    }
}

}

And you can avail yourself of using the custom TextView by create a style for it:

<style name="TextContentStyle" parent="@android:style/TextAppearance.Medium">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">@color/textColorPrimary</item>
    <item name="fontName">OpenSans-Regular.ttf</item>
</style>

And in layout, we use CustomTextView above style:

<com.xx.xx.CustomTextView style="@style/TextContentStyle"
                    android:layout_width="match_parent"
                    android:layout_margin="@dimen/margin_medium"
                    android:gravity="center"
                    android:text="@string/txt_menu"
                    android:textColor="#FFF" />

Moreover, because Typeface.createFromAsset() is not free, so we can optimize code by cache the font which is loaded into memory before.

public class FontCache {
private static Map<String, Typeface> fontMap = new HashMap<String, Typeface>();

public static Typeface getFont(Context context, String fontName){
    if (fontMap.containsKey(fontName)){
        return fontMap.get(fontName);
    }
    else {
        Typeface tf = Typeface.createFromAsset(context.getAssets(), fontName);
        fontMap.put(fontName, tf);
        return tf;
    }
}

}

That's it! I prefer this way because we can use any font type at anywhere that we want, use multiple font type in an app.

topcbl
  • 799
  • 6
  • 20
  • Hm... I don't need to cahnge the font of the application, What i want is to use font-face in the html of webview. Now, I am using the webfont like 'penDataHtml = penDataHtml.replaceAll("","");' but I don't want to use the webfont. Thanks – Adrian Sep 13 '16 at 06:43
  • @Adrian. Custom font in webview is a different story. We can only use custom font in css for sure. font-face { font-family: 'MyCustomFont'; src: url('/assets/fonts/MaycustomFont.ttf') } – topcbl Sep 13 '16 at 06:50
  • Ah?? is it different problem?? so do i have to use csutom font in css like this? ' font-face { font-family: 'MyCustomFont'; src: url('/assets/fonts/MaycustomFont.ttf') } ' with 'wv.loadDataWithBaseURL("file:///android_asset/fonts", cvtHtml, "text/html", "UTF-8", "");' ? – Adrian Sep 13 '16 at 07:02
  • I think so. You can take a look into WebView code, it basically is AbsoluteLayout which render html code and css code, and have no set font method or something like this. You should consider you another View type in android instead of WebView – topcbl Sep 13 '16 at 07:09
0

You can achive this in two way

  1. You can add and use your .ttf (font files) in to assets and use it like this :

    Typeface myTypeface = Typeface.createFromAsset(getAssets(),"fonts/myFont.ttf"); TextView myTextView = (TextView)findViewById(R.id.myTextView); myTextView.setTypeface(myTypeface);

  2. If you do not want to add font files in your application but want to provide different font which can be apply you should get fonts from the applications which are already installed on device like this :

First get the application packages installed on device like this:

String packName = null;
AssetManager assetManager;
Context assetsContext;
String files[];
ArrayList<String> fontList;


private ArrayList<String> getPackName() {
        ArrayList<String> packageName = new ArrayList<String>();
        final PackageManager pm = getPackageManager();
        List<ApplicationInfo> packages = pm
                .getInstalledApplications(PackageManager.GET_META_DATA);
        for (ApplicationInfo packageInfo : packages) {
            packageName.add(packageInfo.packageName);
        }
        return packageName;
    }


//Now get the assets like this

private void getRes(Context appPackContext, ArrayList<String> appPack) {
        ArrayList<String> mPackageList = appPack;
        String defPath = "fonts";
        for (String packageName : mPackageList) {
            packName = packageName;
            assetsContext = getFontAssetsContext(appPackContext, packName);
            assetManager = assetsContext.getAssets();
            try {
                files = assetManager.list(defPath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    fontsItems = new FontsItems();
                    fontList.add(files[i]); // here you get the files which are in given path (You can filter this if need)

                }
            }
        }
    }


    private Context getFontAssetsContext(Context c, String packName) {

        try {
            return c.createPackageContext(packName,
                    Context.CONTEXT_IGNORE_SECURITY);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return c;

    }

I have successfully run this code and it works great for me , hope this helps you too.

Sagar Thakarar
  • 261
  • 3
  • 20