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

Use Roboto font in app with minimum API level 14

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

有没有一种方法可以使用Roboto而不将Roboto字体作为资产?


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

没有,没有其他方法可以针对API 11 <。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
        }
}

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

1
2
3
4
5
<com.my.package.TextView_Roboto>
  android:layout_width="..."
  android:layout_height="..."
  [...]
</com.my.package.TextView_Roboto>

当然,您可以创建一个TextView布局。 一个用于Pre HC,一个用于HC及以上版本(您必须使用layout和layout-v11文件夹)。 现在,您可以使用标记将TextView包含在布局中。 您只需要执行以下操作即可:

1
2
3
4
5
6
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,如下所示:

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