zoukankan      html  css  js  c++  java
  • Android开发之字体设置

    默认字体

    Android SDK自带了四种字体:"normal"“monospace",“sans”, “serif”,如下:


     
    字体

    看这四兄弟长的还是蛮像,我是看不出多大差别。。。

    设置方式

    1.通过XML文件设置

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="monospace"
    android:textSize="20dp"
    android:textColor="#000000"
    android:typeface="monospace"
    android:layout_margin="5dp"/>

    2.Java代码中设置

     TextView txtNormal = (TextView) findViewById(R.id.txt_normal);
        txtNormal.setTypeface(Typeface.MONOSPACE);

    设置第三方字体

    Res中使用

    右键选择项目的app / res文件夹,然后选择New > Android resource directory。


     
    image.png

    Resource type中选择font,File name名为font。


     
    image.png

    将字体文件拷贝到font中


     
    image.png

    java代码中使用

     TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica);
        Typeface typeface = ResourcesCompat.getFont(this, R.font.helvetica);
        txtNormal.setTypeface(typeface);

    Assets中使用

    新建Assets及fonts目录,并将字体文件拷贝到fonts目录下


     
    拷贝字体

    在java代码中使用

     TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica);
        Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");
        txtNormal.setTypeface(typeface);

    第三方框架全局字体设置

    这里推荐一个第三方字体设置库Calligraphy,详细可以点击连接

    添加依赖

     compile 'uk.co.chrisjenx:calligraphy:2.3.0'

    新建Application

    public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/Helvetica.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build()
        );
    }
    }

    在Activity中重写attachBaseContext方法

      @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    在xml中使用

     <TextView
        android:id="@+id/txt_helvetica"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lorem ipsum"
        android:textSize="20dp"
        android:textColor="#000000"
        android:layout_margin="5dp"
        fontPath="fonts/Helvetica.ttf"
        tools:ignore="MissingPrefix"/>

    如果fontPath="fonts/Helvetica.ttf"报错,在View上添加 tools:ignore="MissingPrefix”即可。
    其他具体功能,详见Calligraphy

  • 相关阅读:
    selenium 清空文本几种方法
    python之Chrome 启动参数
    python, selenium 之屏蔽提示框
    myeclipse 安装flex插件后变为中文 修改配置文件切换到英文界面
    用ant编译打包时 警告:编码 GBK 的不可映射字符
    redhat5.1上安装oracle 10.2g客户端及配置使用
    tomcat 1)启动时不识别执行启动命令 2)启动报错 3)关闭不了,用myEclipse启动时显示jvm_bind,端口占用
    virtualBox redhat 共享文件夹 安装增强功能
    ant 内存空间不足
    Linux (ubuntu和redhat) 常用命令及细节
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/10739864.html
Copyright © 2011-2022 走看看