博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android 自定义字体_Android自定义字体教程
阅读量:2532 次
发布时间:2019-05-11

本文共 10018 字,大约阅读时间需要 33 分钟。

android 自定义字体

In this tutorial, we’ll explain how to set up android custom fonts in TextViews and Buttons in our application.

在本教程中,我们将说明如何在应用程序的TextViews和Buttons中设置android自定义字体。

Android自定义字体 (Android Custom Fonts)

Android SDK comes with a set of standard fonts that can be styled by using a few XML attributes. Let’s look at them.

Android SDK附带了一组标准字体,可以使用一些XML属性来设置样式。 让我们看看它们。

  • android:fontFamily : This is used to change the default fonts of the application. We can choose the font from among the following types.

    The default fontFamily is sans-serif.

    android:fontFamily requires minimum API level as 16.

    android:fontFamily :这用于更改应用程序的默认字体。 我们可以从以下类型中选择字体。

    默认的fontFamily是sans-serif

    android:fontFamily需要的最低API级别为16。

  • android:typeface : This XML attribute won’t have any effect if the fontFamily is already used(Unless the API level is less than 15, in which case the fontFamily attribute would be ignored). normal or sans is the default type of this attribute. Following are the values acceptable.

    android:typeface :如果已经使用了fontFamily,则此XML属性将无效(除非API级别小于15,在这种情况下,fontFamily属性将被忽略)。 normal或sans是此属性的默认类型。 以下是可接受的值。
  • android:textStyle : This attribute takes in values : bold, italic and normal either individually or combined such as android:textStyle=”bold|italic”.

    android:textStyle :此属性可以单独或结合使用值: 粗体斜体和普通,例如android:textStyle=”bold|italic”

Let’s club android:fontFamily and android:textStyle and display the different variants of a TextView.

让我们android:textStyle android:fontFamilyandroid:textStyle并显示TextView的不同变体。

The styles.xml which contains the different style variants is given below.

下面给出了包含不同样式变体的styles.xml。

The activity_main.xml is given below.

下面给出activity_main.xml。

To set custom fonts on a TextView/Button/EditText object, the Typeface property is used.

The Typeface class specifies the typeface and intrinsic style of a font.
To set a typeface over a TextView we invoke the method setTypeface().
Following are the Typeface constants that can be used.

若要在TextView / Button / EditText对象上设置自定义字体,请使用Typeface属性。

Typeface类指定字体的字体和固有样式。
要在TextView上设置字体,我们调用方法setTypeface()。
以下是可以使用的Typeface常量。

  • BOLD

    胆大
  • BOLD_ITALIC

    加粗斜体
  • ITALIC

    意大利文
  • NORMAL

    正常

To set custom fonts on our Views, we first need to import the font files into our project.

Font files generally come up in two types .ttf (True Type Font) and .otf (Open Type Font).

要在我们的视图上设置自定义字体,我们首先需要将字体文件导入到我们的项目中。

字体文件通常以.ttf(True Type字体).otf(Open Type字体)两种类型出现。

Android自定义字体项目结构 (Android Custom Fonts Project Structure)

In the above image a new folder
assets has been added under the main directory.

在上图中,新文件夹资产已添加到主目录下。

Android自定义字体代码 (Android Custom Fonts Code)

We’ve created another layout namely activity_custom_fonts.xml for setting custom fonts on our Views.

我们创建了另一个布局,即activity_custom_fonts.xml用于在视图上设置自定义字体。

We’re setting our custom fonts in the java code. The MainActivity.java is given below

我们正在Java代码中设置自定义字体。 MainActivity.java在下面给出

public class MainActivity extends AppCompatActivity {    TextView ambleBold, ambleLight, ambleRegular, openSansItalic, openSansRegular;    Button btn;    private String A_BOLD= "Amble-Bold.ttf";    private String A_LIGHT="Amble-Light.ttf";    private String A_REGULAR= "Amble-Regular.ttf";    private String O_ITALIC= "OpenSans-Italic.ttf";    private String O_REGULAR="OpenSans-Regular.ttf";    private String P_REGULAR="Pacifico.ttf";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_custom_fonts);        ambleBold=(TextView)findViewById(R.id.ambleBold);        ambleLight=(TextView)findViewById(R.id.ambleLight);        ambleRegular=(TextView)findViewById(R.id.ambleRegular);        openSansRegular=(TextView)findViewById(R.id.opRegular);        openSansItalic=(TextView)findViewById(R.id.opItalic);        btn=(Button)findViewById(R.id.pacifico);        ambleBold.setTypeface(Typeface.createFromAsset(getAssets(), A_BOLD));        ambleLight.setTypeface(Typeface.createFromAsset(getAssets(), A_LIGHT));        ambleRegular.setTypeface(Typeface.createFromAsset(getAssets(), A_REGULAR));        openSansRegular.setTypeface(Typeface.createFromAsset(getAssets(), O_REGULAR));        openSansItalic.setTypeface(Typeface.createFromAsset(getAssets(), O_ITALIC));        btn.setTypeface(Typeface.createFromAsset(getAssets(), P_REGULAR));    }}

In the above code we’re calling createFromAsset() method on the Typeface class to create a new instance of the Typeface. An instance of the application’s AssetManager is called by passing getAssets() as the first parameter. The custom font asset file path is passed as a string in the second parameter. Since we’ve placed the font files in the root of assets directory, passing the font filenames would suffice.

在上面的代码中,我们在Typeface类上调用createFromAsset()方法来创建Typeface的新实例。 通过将getAssets()作为第一个参数来调用应用程序AssetManager的实例。 自定义字体资产文件路径在第二个参数中作为字符串传递。 由于我们已将字体文件放置在资产目录的根目录中,因此传递字体文件名就足够了。

Note: Setting external fonts using android:typeface doesn’t work

注意 :使用android:typeface设置外部字体无效

We end up with the following output when the application is run.

运行该应用程序时,我们得到以下输出。

Isn’t it a time consuming and redundant task to set the typeface individually for each of the views?

We need a better alternative. Our answer lies in Custom Views. In the next section, we’ll be creating a Custom TextView class and define custom XML attributes to set the external fonts in the XML layout itself.

为每个视图分别设置字体是一项耗时且冗长的工作吗?

我们需要更好的选择。 我们的答案在于自定义视图 。 在下一节中,我们将创建一个Custom TextView类并定义自定义XML属性,以在XML布局本身中设置外部字体。

Our Updated Project Structure is given below

我们更新的项目结构如下

Before we implement our CustomTextView.java, let’s look into the TypeFactory.java class as shown below.

在实现CustomTextView.java之前,让我们研究一下TypeFactory.java类,如下所示。

public class TypeFactory {    private String A_BOLD= "Amble-Bold.ttf";    private String A_LIGHT="Amble-Light.ttf";    private String A_REGULAR= "Amble-Regular.ttf";    private String O_ITALIC= "OpenSans-Italic.ttf";    private String O_REGULAR="OpenSans-Regular.ttf";    Typeface ambleBold;    Typeface ambleLight;    Typeface ambleRegular;    Typeface openSansItalic;    Typeface openSansRegular;    public TypeFactory(Context context){        ambleBold = Typeface.createFromAsset(context.getAssets(),A_BOLD);        ambleLight = Typeface.createFromAsset(context.getAssets(),A_LIGHT);        ambleRegular = Typeface.createFromAsset(context.getAssets(),A_REGULAR);        openSansItalic = Typeface.createFromAsset(context.getAssets(),O_ITALIC);        openSansRegular = Typeface.createFromAsset(context.getAssets(),O_REGULAR);    }}

The above code essentially creates a custom typeface font for each of the font files. We can now use the class variables in our CustomTextView to set the font accordingly.

上面的代码实际上为每个字体文件创建了一个自定义字体。 现在,我们可以在CustomTextView中使用类变量来相应地设置字体。

The CustomTextView.java class is given below.

下面给出了CustomTextView.java类。

public class CustomTextView extends TextView {    private int typefaceType;    private TypeFactory mFontFactory;    public CustomTextView(Context context, AttributeSet attrs) {        super(context, attrs);        applyCustomFont(context, attrs);    }    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        applyCustomFont(context, attrs);    }    public CustomTextView(Context context) {        super(context);    }    private void applyCustomFont(Context context, AttributeSet attrs) {        TypedArray array = context.getTheme().obtainStyledAttributes(                attrs,                R.styleable.CustomTextView,                0, 0);        try {            typefaceType = array.getInteger(R.styleable.CustomTextView_font_name, 0);        } finally {            array.recycle();        }        if (!isInEditMode()) {            setTypeface(getTypeFace(typefaceType));        }    }    public Typeface getTypeFace(int type) {        if (mFontFactory == null)            mFontFactory = new TypeFactory(getContext());        switch (type) {            case Constants.A_BOLD:                return mFontFactory.ambleBold;            case Constants.A_LIGHT:                return mFontFactory.ambleLight;            case Constants.A_REGULAR:                return mFontFactory.ambleRegular;            case Constants.O_LIGHT:                return mFontFactory.openSansItalic;            case Constants.O_REGULAR:                return mFontFactory.openSansRegular;            default:                return mFontFactory.ambleBold;        }    }    public interface Constants {        int A_BOLD = 1,                A_LIGHT = 2,                A_REGULAR = 3,                O_LIGHT = 4,        O_REGULAR=5;    }}

R.styleable.CustomTextView is defined inside the attrs.xml file as shown below.

R.styleable.CustomTextView在attrs.xml文件中定义,如下所示。

The attribute font_name is the custom attribute we’ll be using in the XML layout.

属性font_name是我们将在XML布局中使用的自定义属性。

Our updated activity_custom_fonts.xml layout is given below:

我们更新后的activity_custom_fonts.xml布局如下:

The MainActivity.java code now would just require setting the Button typeface.

现在,MainActivity.java代码仅需要设置Button字体。

Note: A CustomButton Custom View can be created in a similar way. Try that out!

注意 :可以用类似的方式创建CustomButton自定义视图。 试试看!

This brings an end to this tutorial. You can download the Android CustomFonts Tutorial from the below link.

本教程到此结束。 您可以从下面的链接下载Android CustomFonts教程

翻译自:

android 自定义字体

转载地址:http://iqlzd.baihongyu.com/

你可能感兴趣的文章
Git(四) - 分支管理
查看>>
PHP Curl发送数据
查看>>
HTTP协议
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Ubuntu菜鸟入门(五)—— 一些编程相关工具
查看>>
valgrind检测linux程序内存泄露
查看>>
Hadoop以及组件介绍
查看>>
1020 Tree Traversals (25)(25 point(s))
查看>>
第一次作业
查看>>
“==”运算符与equals()
查看>>
单工、半双工和全双工的定义
查看>>
Hdu【线段树】基础题.cpp
查看>>
时钟系统
查看>>
BiTree
查看>>
5个基于HTML5的加载动画推荐
查看>>
水平权限漏洞的修复方案
查看>>
静态链接与动态链接的区别
查看>>