我试图在Android Studio中使用自定义字体,就像我们在Eclipse中所做的那样。但不幸的是,不知道在哪里放“资产”文件夹!


当前回答

我认为我们可以使用谷歌字体而不是下载。ttf文件。这很容易实现。你只需要遵循这些步骤。 步骤1)打开你的项目的layout.xml和属性中的文本视图的选择字体家族(作为参考截图附在后面)

步骤2)in字体家族选择更多字体..选项,如果你的字体不在那里。然后你会看到一个新的窗口将打开,在那里你可以输入你需要的字体,并从列表中选择所需的字体,即常规,粗体,斜体等。如下图所示。

步骤3)然后你会看到一个字体文件夹将自动生成在/res文件夹有你选择的字体xml文件。

然后你可以直接在xml中使用这个字体家族作为

      android:fontFamily="@font/josefin_sans_bold"

或者从专业语法上讲,你可以使用

  Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
  fontText.setTypeface(typeface);

其他回答

把字体放在资产文件夹 然后应用fontfamily: " your fonts

将字体添加到app/src/main/assets的assets文件夹中 像这样创建一个自定义文本视图:

class CustomLightTextView : TextView {

constructor(context: Context) : super(context){
    attachFont(context)
}
constructor(context: Context, attrs: AttributeSet):    super(context, attrs){
    attachFont(context)
}
constructor(context: Context, attrs: AttributeSet?,    defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    attachFont(context)
}
fun attachFont(context: Context) {
    this.setTypeface(FontCache.getInstance().getLightFont(context))
}

}

添加FontCache:这样你就不必像这样一遍又一遍地创建字体:

class FontCache private constructor(){

val fontMap = HashMap<String,Typeface>()

companion object {
    private var mInstance : FontCache?=null
    fun getInstance():FontCache = mInstance?: synchronized(this){
        return mInstance?:FontCache().also { mInstance=it }
    }
}

fun getLightFont(context: Context):Typeface?{
    if(!fontMap.containsKey("light")){
        Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf");
        fontMap.put("light",Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf"))
    }
    return fontMap.get("light")
}

}

这样就完成了!

附注:从android O,你可以直接添加字体。

Android 8.0 (API 26)引入了与字体相关的新功能。

1)字体可以作为资源使用。

2)可下载的字体。

如果你想在android应用程序中使用外部字体,你可以在apk中包含字体文件或配置可下载的字体。

在APK中包含字体文件:您可以下载字体文件,保存在res/字体文件器中,定义字体族,并在样式中使用字体族。

有关使用自定义字体作为资源的更多详细信息,请参阅http://www.zoftino.com/android-using-custom-fonts

配置可下载字体:通过提供字体提供程序详细信息来定义字体,添加字体提供程序证书并在样式中使用字体。

有关可下载字体的详细信息,请参阅http://www.zoftino.com/downloading-fonts-android

现在有很多应用字体的方法,最简单的方法之一是这样的, 1)右键单击res文件夹 进入“新建> Android资源目录”。

2)从资源类型列表中选择字体,然后单击确定。

3)把你的字体文件放在字体文件夹里。

有很多方法来设置自定义字体家族在字段和我使用如下。

添加字体作为资源,在Android Studio中执行以下步骤:

1)右键单击res文件夹,进入New > Android资源目录。出现“新建资源目录”窗口。

2)在“资源类型”列表中选择“字体”,单击“确定”。

注意:资源目录名必须为字体。

3)在字体文件夹中添加你的字体文件。

在xml文件中添加所需视图中的字体:

注:但你需要做到以下几点:

Android Studio 3.0以上的金丝雀。 你的Activity扩展了AppCompatActivity。 像这样更新你的Gradle文件:

    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {        
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

buildtoolsVersion以上26和最低targetSdkVersion要求26

在构建中添加依赖项。gradle文件:

classpath 'com.android.tools.build:gradle:3.0.0-beta4'

gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip