Android - 使用字体文件,自定义View代替图标

    xiaoxiao2021-04-17  38

    唠叨

    今天无意中看到了 material-design-iconic-font ,就想着使用该字体文件使用TextView显示Unicode图标。

    1. 引入 字体文件

    下载字体文件后,与 res 资源文件同级新建 assets/fonts 文件夹 ,复制进去;


    2. FontUtils

    自定义 Font工具类,加载所有的字体 TypeFace , 以便使用;

    public class FontUtils { private static Typeface iconFace; public static Typeface getIconTypeFace() { if (iconFace == null) { synchronized (FontUtils.class) { if (iconFace == null) { iconFace = Typeface.createFromAsset(CoreApplication.getInstance().getAssets(), "fonts/Material-Design-Iconic-Font.ttf"); } } } return iconFace; } // 当然也可以加载 其他的字体文件,给textview使用 }

    3. 自定义 IconView

    继承 AppCompatTextView , 当然你也可以加载其他类型的字体,这样你的App就显示为其他字体的样式!

    public class IconView extends AppCompatTextView { public IconView(Context context) { super(context); init(context); } public IconView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public IconView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { this.setTypeface(FontUtils.getIconTypeFace()); } }

    4. 使用

    可以自定义颜色和大小

    string.xml

    <string name="icon_keyboard_hide">\uf2a3</string>

    引入

    <com.smartahc.android.core_ui.weight.IconView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/icon_keyboard_hide" android:textColor="@color/blue_light" android:layout_centerInParent="true" android:textSize="50sp"/>

    更多 unicode 图标见 : material-design-iconic-font/icons

    记住 前面加入 \u , 比如 下面的 \uf3e9


    5.注意

    不要在 application 中加载字体文件不要在IconView中加载字体文件 , 虽然存在 Context , 每次加载都浪费资源!
    转载请注明原文地址: https://ju.6miu.com/read-673730.html

    最新回复(0)