Android textview设置ttf字体库本地库和网络库使用的两种方式

在这里插入图片描述

一:从assets中加载
将相关ttf字体库放入assets/fonts文件夹下,注意ttf文件名称不能是中文

// 加载assets中的字体
TextView textView1 = (TextView) findViewById(R.id.textView1);

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/1.ttf");

textView1.setTypeface(typeface);

二:因第一种方式占用的体积很大,编译后的包会很大所以可以动态从服务器中拿到下载地址进行下载至本地后使用
下载工具类

public class EditImageFontUtls {

    /**
     * 获取对应字体
     *
     * @param context
     * @param name    存储本地名称(英文命名)
     * @return url 下载地址
     */
    public static void getTypeface(Activity context, String name, String url, OnDownloadListener onDownloadListener) {
        try {
            boolean isExists = fileIsExists(getFontPath(context) + name + ".ttf");
            if (isExists) {
                if (onDownloadListener != null) {
                    onDownloadListener.onTypeface(Typeface.createFromFile(getFontPath(context) + name + ".ttf"));
                }
            } else {
                downLoadFont(context, name, url, new OnDownloadListener() {
                    @Override
                    public void onTypeface(Typeface typeface) {
                        if (onDownloadListener != null) {
                            onDownloadListener.onTypeface(typeface);
                        }
                    }

                    @Override
                    public void onProgress(double progress) {
                        //下载中
                        if (onDownloadListener != null) {
                            onDownloadListener.onProgress(progress);
                        }
                    }
                });
            }
        } catch (Exception e) {

        }
    }

    //fileName 为文件名称 返回true为存在
    public static boolean fileIsExists(String fileName) {
        try {
            File f = new File(fileName);
            if (f.exists()) {
                Log.i("fileIsExists", "有这个文件");
                return true;
            } else {
                Log.i("fileIsExists", "没有这个文件");
                return false;
            }
        } catch (Exception e) {
            Log.i("fileIsExists", "崩溃");
            return false;
        }
    }

    //获取存取字体的路径
    public static String getFontPath(Context context) {
        return "/data/data/" + context.getPackageName() + "/ttf_files/";
    }

    /**
     * 下载字体库 保存在本地 例如: /data/data/包名/ttf_files/huawencaiyun.ttf
     * @param context
     * @param name 保存到本地文件名称(不能是中文命名)
     * @param url 字体库下载地址
     * @param onDownloadListener
     */
    public static void downLoadFont(Activity context, String name, String url, OnDownloadListener onDownloadListener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream outputStream = null;
                try {
                    OkHttpClient client = new OkHttpClient.Builder().build();
                    ;
                    Request request = (new Request.Builder()).url(url).get().build();
                    Call call = client.newCall(request);
                    Response response = call.execute();
                    ResponseBody body = response.body();
                    InputStream inputStream = body.byteStream();
                    long lengh = body.contentLength();
                    String file_name = getFontPath(context) + name + ".ttf";
                    File file = new File(getFontPath(context));
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    outputStream = new FileOutputStream(file_name);
                    int losing = 0;
                    byte[] bytes = new byte[1024];
                    while (true) {
                        int read = inputStream.read(bytes);
                        if (read == -1) {
                            outputStream.flush();
                            inputStream.close();
                            outputStream.close();
                            Log.i("downLoadFont", "下载完成***********");
                            Log.i("downLoadFont", "下载地址" + file_name);
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (onDownloadListener != null) {
                                        onDownloadListener.onTypeface(Typeface.createFromFile(getFontPath(context) + name + ".ttf"));
                                    }
                                }
                            });
                            return;
                        }

                        outputStream.write(bytes, 0, read);
                        losing += read;
                        double i = (double) losing / (double) lengh;
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (onDownloadListener != null) {
                                    Log.i("downLoadFont", "下载进度:" + i * (double) 100 + '%');
                                    onDownloadListener.onProgress(i * (double) 100);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

}

需要使用字体的时候点击调用获取字体的方法,会根据情况走本地获取或者下载

 holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditImageFontUtls.getTypeface(context, fontStyle.get(position).ttfName, fontStyle.get(position).url, new OnDownloadListener() {
                    @Override
                    public void onTypeface(Typeface typeface) {
                    //设置字体库
                        holder.tvName.setTypeface(typeface);
                    }

                    @Override
                    public void onProgress(double progress) {
                    //下载进度
                        holder.progressLayout.setProgress((float) progress);
                    }
                });
            }
        });

接口回调

public interface OnDownloadListener {
    void onTypeface(Typeface typeface);//字体样式

    void onProgress(double progress);//下载进度
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在布局文件中为 TextView 设置字体: ```xml <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textSize="20sp" android:fontFamily="sans-serif" /> ``` 在代码中为 TextView 设置字体: ```java TextView textView = findViewById(R.id.text_view); textView.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf")); ``` 如果你的字体文件在 assets/fonts/ 目录下,并且文件名为 myfont.ttfAndroid 8.0 以上可以使用以下方式设置 ```xml <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textSize="20sp" android:fontFamily="@font/myfont" /> ``` 然后将字体文件放入 res/font/ 目录下,并命名为 myfont.ttf ``` ### 回答2: 在Android开发中,TextView是常用的控件之一,通过TextView可以展示文本信息。但是有时候,我们需要自定义字体,以便更好地适应我们的设计需求和风格。 那么如何在TextView设置自定义字体呢?下面详细介绍: 首先,首先你需要准备字体文件,一般字体文件的格式是.ttf或.otf,必须放在res/font或assets文件夹下。 接着,我们需要定义一个自定义字体的文件夹。如果字体文件被放在res/font下,则需要在res文件夹下定义一个font文件夹。如果字体文件被放在assets下,则需要在main文件夹下定义一个fonts文件夹。 定义完字体文件夹后,我们可以在TextView中通过代码来设置字体。主要有以下几个方法: 1. setTypeface方法:通过该方法设置TextView字体,可以选择系统自带的字体,也可以选择自定义字体。 示例代码: //设置TextView字体为系统自带的sans-serif-bold textView.setTypeface(Typeface.DEFAULT_BOLD); //设置TextView字体为自定义字体 Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/impact.ttf"); textView.setTypeface(tf); 2. setTextAppearance方法:该方法可以通过指定样式来设置TextView字体,样式可以是系统样式,也可以是自定义样式。 示例代码: //使用系统提供的样式为TextView设置字体 textView.setTextAppearance(android.R.style.TextAppearance_DeviceDefault_Large); //定义自定义样式 <style name="CustomTextStyle"> <item name="android:textSize">20sp</item> <item name="android:textColor">#666666</item> <item name="android:fontFamily">@font/impact</item> </style> //使用自定义样式为TextView设置字体 textView.setTextAppearance(R.style.CustomTextStyle); 3. 在布局文件中设置字体:可以在布局文件中使用TextView标签中的android:fontFamily属性来指定字体。 示例代码: <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:fontFamily="@font/impact" /> 总之,以上是在Android设置TextView的自定义字体的几种方法,可以根据实际情况进行选择使用。此外,我们还可以使用SpannableStringBuilder来设置富文本样式,包括字体样式。 ### 回答3: Android开发中,TextView是常用的控件之一。我们可以通过代码或xml文件来设置TextView的属性,包括字体属性。下面我们就来讲讲如何设置TextView字体。 一、使用字体文件 1. 在assets目录下创建一个fonts目录,把字体文件放在fonts目录下,如assets/fonts/MyFont.ttf。 2. 在res目录下创建一个xml目录,创建一个名为font_path.xml的文件。 3. 在文件中添加以下代码: ``` <?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android"> <font android:font="@font/MyFont" android:fontStyle="normal" android:fontWeight="400" /> </font-family> ``` 4. 在xml文件中设置TextView字体,代码如下: ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:fontFamily="@font/font_path" /> ``` 二、使用系统字体 1. 在xml文件中设置TextView字体,代码如下: ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:fontFamily="sans-serif" /> ``` 2. 如果要使用其他系统字体,可以在fontFamily属性中设置字体名称,如: ``` android:fontFamily="serif" ``` 三、使用第三方 1. 在app/build.gradle文件中的dependencies添加以下代码: ``` dependencies { implementation 'uk.co.chrisjenx:calligraphy:2.3.0' } ``` 2. 在Application中初始化Calligraphy,代码如下: ``` @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/MyFont.ttf") .setFontAttrId(R.attr.fontPath) .build()); } ``` 3. 在xml文件中设置TextView字体,代码如下: ``` <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:fontPath="@string/font_path" /> ``` 以上就是几种设置TextView字体的方法,大家可以根据自己的需求选择适合自己的方法,希望对大家有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值