自定义字体和XML布局(Android)

发布于 2021-02-02 23:02:38

我正在尝试使用Android中的XML文件定义GUI布局。据我所知,没有办法指定您的小部件应在XML文件中使用一种自定义字体(例如,您放置在资产/字体/中的字体),并且只能使用系统安装的字体。

我知道,在Java代码中,我可以使用唯一ID手动更改每个小部件的字体。另外,我可以遍历Java中的所有小部件以进行此更改,但这可能会很慢。

我还有什么其他选择?有没有更好的方法来制作具有自定义外观的小部件?我特别不想为添加的每个新小部件手动更改字体。

关注者
0
被浏览
504
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    TextViewPlus.java:

    package com.example;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.widget.TextView;
    
    public class TextViewPlus extends TextView {
        private static final String TAG = "TextView";
    
        public TextViewPlus(Context context) {
            super(context);
        }
    
        public TextViewPlus(Context context, AttributeSet attrs) {
            super(context, attrs);
            setCustomFont(context, attrs);
        }
    
        public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setCustomFont(context, attrs);
        }
    
        private void setCustomFont(Context ctx, AttributeSet attrs) {
            TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
            String customFont = a.getString(R.styleable.TextViewPlus_customFont);
            setCustomFont(ctx, customFont);
            a.recycle();
        }
    
        public boolean setCustomFont(Context ctx, String asset) {
            Typeface tf = null;
            try {
            tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
            } catch (Exception e) {
                Log.e(TAG, "Could not get typeface: "+e.getMessage());
                return false;
            }
    
            setTypeface(tf);  
            return true;
        }
    
    }
    

    attrs.xml:(以res / values为单位)

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="TextViewPlus">
            <attr name="customFont" format="string"/>
        </declare-styleable>
    </resources>
    

    main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:foo="http://schemas.android.com/apk/res/com.example"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <com.example.TextViewPlus
            android:id="@+id/textViewPlus1"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:text="@string/showingOffTheNewTypeface"
            foo:customFont="saxmono.ttf">
        </com.example.TextViewPlus>
    </LinearLayout>
    

    你将在资产文件夹中放入“ saxmono.ttf”



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看