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

前端 未结 8 472
無奈伤痛
無奈伤痛 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:38

    Extend a custom class from TextView and customise font in the class. Then you would be able to use that custom textview class in you xml and you won't need to customize fonts dynamically in your code.

    Good luck.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题