Is it possible to set a custom font for entire of application?

后端 未结 25 2958
日久生厌
日久生厌 2020-11-22 02:44

I need to use certain font for my entire application. I have .ttf file for the same. Is it possible to set this as default font, at application start up and then use it else

25条回答
  •  醉梦人生
    2020-11-22 03:15

    Tom's solution works great, but only works with TextView and EditText.

    If you want to cover most of the views (RadioGroup, TextView, Checkbox...), I created a method doing that :

    protected void changeChildrenFont(ViewGroup v, Typeface font){
        for(int i = 0; i < v.getChildCount(); i++){
    
            // For the ViewGroup, we'll have to use recursivity
            if(v.getChildAt(i) instanceof ViewGroup){
                changeChildrenFont((ViewGroup) v.getChildAt(i), font);
            }
            else{
                try {
                    Object[] nullArgs = null;
                    //Test wether setTypeface and getTypeface methods exists
                    Method methodTypeFace = v.getChildAt(i).getClass().getMethod("setTypeface", new Class[] {Typeface.class, Integer.TYPE});
                    //With getTypefaca we'll get back the style (Bold, Italic...) set in XML
                    Method methodGetTypeFace = v.getChildAt(i).getClass().getMethod("getTypeface", new Class[] {});
                    Typeface typeFace = ((Typeface)methodGetTypeFace.invoke(v.getChildAt(i), nullArgs));
                    //Invoke the method and apply the new font with the defined style to the view if the method exists (textview,...)
                    methodTypeFace.invoke(v.getChildAt(i), new Object[] {font, typeFace == null ? 0 : typeFace.getStyle()});
                }
                //Will catch the view with no such methods (listview...)
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    This method will get back the style of the view set in XML (bold, italic...) and apply them if they exists.

    For the ListView, I always create an adapter, and I set the font inside getView.

提交回复
热议问题