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

后端 未结 25 3122
日久生厌
日久生厌 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 02:55

    I wrote a class assigning typeface to the views in the current view hierarchy and based os the current typeface properties (bold, normal, you can add other styles if you want):

    public final class TypefaceAssigner {
    
    public final Typeface DEFAULT;
    public final Typeface DEFAULT_BOLD;
    
    @Inject
    public TypefaceAssigner(AssetManager assetManager) {
        DEFAULT = Typeface.createFromAsset(assetManager, "TradeGothicLTCom.ttf");
        DEFAULT_BOLD = Typeface.createFromAsset(assetManager, "TradeGothicLTCom-Bd2.ttf");
    }
    
    public void assignTypeface(View v) {
        if (v instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) v).getChildCount(); i++) {
                View view = ((ViewGroup) v).getChildAt(i);
                if (view instanceof ViewGroup) {
                    setTypeface(view);
                } else {
                    setTypeface(view);
                }
            }
        } else {
            setTypeface(v);
        }
    }
    
    private void setTypeface(View view) {
        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            Typeface typeface = textView.getTypeface();
            if (typeface != null && typeface.isBold()) {
                textView.setTypeface(DEFAULT_BOLD);
            } else {
                textView.setTypeface(DEFAULT);
            }
        }
    }
    }
    

    Now in all fragments in onViewCreated or onCreateView, in all activities in onCreate and in all view adapters in getView or newView just invoke:

    typefaceAssigner.assignTypeface(view);
    

提交回复
热议问题