Set font for all textViews in activity?

后端 未结 8 2450
忘了有多久
忘了有多久 2020-11-28 06:07

Is it possible to set the font for all the TextViews in a activity? I can set the font for a single textView by using:

    TextView tv=(TextView)findViewByI         


        
相关标签:
8条回答
  • 2020-11-28 06:49

    The one from my personal collection:

    private void setFontForContainer(ViewGroup contentLayout) {
        for (int i=0; i < contentLayout.getChildCount(); i++) {
            View view = contentLayout.getChildAt(i);
            if (view instanceof TextView)
                ((TextView)view).setTypeface(yourFont);
            else if (view instanceof ViewGroup)
                setFontForContainer((ViewGroup) view);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 06:53

    Extending Agarwal's answer... you can set regular, bold, italic, etc by switching the style of your TextView.

    import android.content.Context;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    public class TextViewAsap extends TextView {
    
        public TextViewAsap(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        public TextViewAsap(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public TextViewAsap(Context context) {
            super(context);
            init();
        }
    
        private void init() {
            if (!isInEditMode()) {
                Typeface tf = Typeface.DEFAULT;
    
                switch (getTypeface().getStyle()) {
                    case Typeface.BOLD:
                        tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Bold.ttf");
                        break;
    
                    case Typeface.ITALIC:
                        tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf");
                        break;
    
                    case Typeface.BOLD_ITALIC:
                        tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf");
                        break;
    
                    default:
                        tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Regular.ttf");
                        break;
                }
    
                setTypeface(tf);
            }
        }
    
    }
    

    You can create your Assets folder like this:

    And your Assets folder should look like this:

    Finally your TextView in xml should be a view of type TextViewAsap. Now it can use any style you coded...

    <com.example.project.TextViewAsap
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Example Text"
                    android:textStyle="bold"/>
    
    0 讨论(0)
提交回复
热议问题