Set font at runtime, TextView

前端 未结 9 664
温柔的废话
温柔的废话 2020-11-29 22:00

How to set the font of a TextView created at runtime?

I created a TextView

Textview tv = new TextView(this);      
tv.setTextSize(20);

9条回答
  •  春和景丽
    2020-11-29 22:13

    You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont method at the end of your Activity onCreate method or whenever you dynamically create new views:

    private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
    private static Typeface m_font = null;
    
    public static Typeface getFont(Context p_context)
    {
        if (null == m_font && null != p_context)
        {
            m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
        }
        return m_font;
    }
    
    public static void setViewGroupFont(ViewGroup p_viewGroup)
    {
        if (null != p_viewGroup)
        {
            for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
            {
                View currChildView = p_viewGroup.getChildAt(currChildIndex);
    
                if (ViewGroup.class.isInstance(currChildView))
                {
                    setViewGroupFont((ViewGroup) currChildView);
                }
                else
                {
                    try
                    {
                        Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);
    
                        setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
                    }
                    catch (NoSuchMethodException ex)
                    {
                        // Do nothing
                    }
                    catch (Exception ex)
                    {
                        // Unexpected error setting font
                    }
                }
            }
        }
    }
    

提交回复
热议问题