在 android 中设置字体

Set font face in android

我想将一些 textview 字体更改为外部字体,我做了这样的事情:

typeFace = Typeface.createFromAsset(getAssets(),"fonts/bkoodak.ttf");
tv1.setTypeface(typeFace);
tv2.setTypeface(typeFace);
tv3.setTypeface(typeFace);
...

但这种形式对我来说并不好。 有什么方法可以做得更好吗?

您可以创建自己的 TextView class:

public class MyTextView extends TextView {

        public MyTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(attrs);
        }

        public MyTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(attrs);

        }

        public MyTextView(Context context) {
            super(context);
            init(null);
        }

        private void init(AttributeSet attrs) {
            if (attrs != null) {
                TypedArray a = getContext().obtainStyledAttributes(attrs,
                        R.styleable.MyTextView);

                Typeface myTypeface = Typeface.createFromAsset(getContext()
                        .getAssets(), "fonts/bkoodak.ttf");
                setTypeface(myTypeface);

                a.recycle();
            }
        }

    }

并在您的布局中使用它:

 <yourpackage.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

是的,有更好的方法。

但是您必须创建自己的应用 TypeFace 的派生 TextView。并在您的 XML 布局中使用它。

更多细节请参考这个问题: How to make a custom TextView?

您可以创建一个 class 并在任何地方使用它。

例如:

FontChanger Class:

public class FontChanger
{
    private Typeface typeface;

    public FontChanger(Typeface typeface)
    {
        this.typeface = typeface;
    }

    public FontChanger(AssetManager assets, String assetsFontFileName)
    {
        typeface = Typeface.createFromAsset(assets, assetsFontFileName);
    }

    public void replaceFonts(ViewGroup viewTree)
    {
        View child;
        for(int i = 0; i < viewTree.getChildCount(); ++i)
        {
            child = viewTree.getChildAt(i);
            if(child instanceof ViewGroup)
            {
                // recursive call
                replaceFonts((ViewGroup)child);
            }
            else if(child instanceof TextView)
            {
                // base case
                ((TextView) child).setTypeface(typeface);
            }
        }
    }
}

onCreate 你的 activity :

FontChanger fontChanger = new FontChanger(getAssets(), "font.otf");
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));