如何在不使用任何第三方库的情况下在 android 中的所有小部件(操作栏、抽屉和任何文本)中应用自定义字体?

how to apply custom font in all of widgets in android (actionbar,drawer and any text) without using any third party library?

我想在整个应用程序小部件中应用自定义 font(ActionBar,Navigation Drawer,Tabs,Toolbar,Toast)不使用任何第三方库的文本,那么我该如何实现呢? 有什么办法得到这个。

Custom font in android application Widget(Actionbar,Drawer,etc.) Text without any third party .

您可以为此使用属性集: MyTextView.class

public class MyTextView extends TextView {

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

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

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

                private void init(Context c, AttributeSet arts){
                    try {
                        if (!isInEditMode()) {
                            if (arts != null) {

                                TypedArray array = getContext().obtainStyledAttributes(arts, R.styleable.MyViewStyle);
                                String fontName = array.getString(R.styleable.MyViewStyle_font_name);

                                if (fontName != null) {

                                    Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontName);
                                    setTypeface(typeface);
                                }

                                array.recycle();

                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();                           
                    }
                }
            }

attr.xml

<declare-styleable name="MyViewStyle">
    <attr name="font_name" format="string" />
</declare-styleable>

在您的xml中使用此文本视图:

      <com.packg.widgets.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/description_label"           
        app:font_name="your font name" />

Android 也支持字体检查这个 link: fonts

使用所选字体的 .ttf 文件。将其复制到资产文件夹中。像这样向 TypeFace 提供该字体文件的路径。

TypeFace mTypeFace = Typeface.createFromAsset(getAssets(), "expressway.ttf");
TextView txt = (TextView) findViewById(R.id.text);
txt.setTypeface(mTypeFace); 

到目前为止,
无法使用 Android API 将全局字体应用于整个应用程序中的所有 TextView,尽管 Android O 引入了一项新功能,[=24= 中的字体] ],它允许您将字体用作资源。

将此 link 引用到 Learn more

如果我们谈论图书馆,最著名的图书馆可以为您解决问题。检查一下 - Calligraphy。 Github 页面对您如何使用以及背后的工作原理有更好的解释。

Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources.

  • 您可以在res/font/文件夹中添加字体文件,将字体打包为资源。这些字体编译在您的 R 文件中,并在 Android Studio 中自动可用。
  • 访问一个字体资源,我们可以使用@font/myfont,或者R.font.myfont.

创建字体资源 XML :

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

向 TextView 添加字体:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

以编程方式使用字体:

Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);

FontUtils.java

public class FontUtils {
    private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();
    public static SpannableString actionBar(Activity mActivity, String title) {
        SpannableString s = new SpannableString(title);
        s.setSpan(new TypefaceSpan(mActivity, "simple.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return s;
    }
    public static void overrideFonts(final Activity mActivity) {
        mActivity.getLayoutInflater().setFactory(new LayoutInflater.Factory() {
            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                View v = FontUtils.tryInflate(name, context, attrs);
                if (v instanceof TextView) {
                    FontUtils.setTypeFace((TextView) v, mActivity);
                }
                return v;
            }
        });
    }
    public static Typeface getFonts(Context context, String name) {
        Typeface typeface = TYPEFACE.get(name);
        if (typeface == null) {
            typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"+ name);
            TYPEFACE.put(name, typeface);
        }
        return typeface;
    }
    public static View tryInflate(String name, Context context, AttributeSet attrs) {
        LayoutInflater li = LayoutInflater.from(context);
        View v = null;
        try {
            v = li.createView(name, null, attrs);
        } catch (Exception e) {
            try {
                v = li.createView("android.widget." + name, null, attrs);
            } catch (Exception e1) {
            }
        }
        return v;
    }
    public static void setTypeFace(TextView tv, Context mContext) {
        tv.setTypeface(FontUtils.getFonts(mContext, "simple.ttf"));
    }
}

TypefaceSpan.java

public class TypefaceSpan extends MetricAffectingSpan {
    private static LruCache<String, Typeface> sTypefaceCache =
           new LruCache<String, Typeface>(12);

    private Typeface mTypeface;
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("fonts/%s", typefaceName));
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

里面activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        FontUtils.overrideFonts(YourActivity.this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        //toolbar
        getSupportActionBar().setTitle(FontUtils.actionBar(this, getResources().getString(R.string.app_name)));         
    }

创建字体资源XML :

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

向 TextView 添加字体:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>