How to set custom font in .xml file instead of .java file?

前端 未结 8 479
無奈伤痛
無奈伤痛 2020-12-05 10:14

I am creating one Application in which I want to set custom font.

But I can\'t use custom Fonts in .xml file, for using this I need to initialize each and every Text

8条回答
  •  再見小時候
    2020-12-05 10:39

    Download a ttf file of the font you want to use and paste it in the

    src->main->assets->font.ttf

    Then for using ttf you need to do the following

    for setting that font to particular text do following

       TextView tv_the = (TextView) findViewById(R.id.the);
        Typeface face = Typeface.createFromAsset(getAssets(), "font.ttf");
        tv_the.setTypeface(face);
    

    If you want to set custom font to the whole activity do following

    final ViewGroup mContainer = (ViewGroup) findViewById(android.R.id.content).getRootView();
            final Typeface mFont = Typeface.createFromAsset(getAssets(), "badoni2.ttf");
            Parameters.setAppFont(mContainer, mFont);
    

    and add the Parameters class in your application

    public class Parameters {
    
    public static final void setAppFont(ViewGroup mContainer, Typeface mFont) {
        if (mContainer == null || mFont == null)
            return;
    
        final int mCount = mContainer.getChildCount();
    
        // Loop through all of the children.
        for (int i = 0; i < mCount; ++i) {
            final View mChild = mContainer.getChildAt(i);
            if (mChild instanceof TextView) {
                // Set the font if it is a TextView.
                ((TextView) mChild).setTypeface(mFont);
            } else if (mChild instanceof ViewGroup) {
                // Recursively attempt another ViewGroup.
                setAppFont((ViewGroup) mChild, mFont);
            }
    
        }
    }
    

    Try this and let me know if it work for you

提交回复
热议问题