android - 在最低 API 级别 14 的应用中使用 Roboto 字体

标签 android typeface

我有一个最低 API 级别为 14 的应用。我认为所有兼容设备都应默认安装 Roboto 字体是否正确?如果我将 textView 字体设置为 Roboto 或 Roboto Light,它似乎默认为普通的 sans 字体。

有没有办法在不将 Roboto 字体作为 Assets 的情况下使用 Roboto?

最佳答案

Is there a way to use Roboto without including the Roboto font as an asset?

不,API 11 没有其他方法可以做到这一点<.

我通常为 Robot 字体创建一个自定义 TextView:

public class TextView_Roboto extends TextView {

        public TextView_Roboto(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
                createFont();
        }

        public TextView_Roboto(Context context, AttributeSet attrs) {
                super(context, attrs);
                createFont();
        }

        public TextView_Roboto(Context context) {
                super(context);
                createFont();
        }

        public void createFont() {
                Typeface font = Typeface.createFromAsset(getContext().getAssets(), "robo_font.ttf");
                setTypeface(font);
        }
}

现在您可以像这样在布局中使用它:

<com.my.package.TextView_Roboto>
  android:layout_width="..."
  android:layout_height="..."
  [...]
</com.my.package.TextView_Roboto>

当然你可以创建一个 TextView 布局。一个用于 Pre HC,一个用于 HC 及更高版本(您必须使用 layout 和 layout-v11 文件夹)。现在您可以使用 <include>标记以将 TextView 包含在您的布局中。你只需要这样做:

if (android.os.Build.VERSION.SDK_INT >= 11){
    TextView txt = (TextView) findViewById(R.id.myTxtView);
}
else{
    TextView_Roboto txt = (TextView_Roboto) findViewById(R.id.myTxtView);
}

编辑:

您可以像这样从 Android 4.1+ 原生使用 Roboto:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed

关于android - 在最低 API 级别 14 的应用中使用 Roboto 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631326/

相关文章:

java - 不违反更改列表中的 "compareTo"契约(Contract)

java - 尝试将自定义字体应用于按钮时出现 NullPointerException

android - 更改 TextInputLayout 提示字体

java - Android Webview 中的 Html 音频

actionscript-3 - 嵌入欧美字符

java - 检查 Android 中 Typeface 对象的系列

android - 从字节数组创建 typeFace

java - 设置标注图像 mapbox android

android - SearchView 建议 - 布局宽度 : match_parent

android - 如何在 android 中播放带有增强现实的视频