在app中使用Roboto字体,最低API级别为14

Mil*_*ilo 19 android typeface

我有一个最低API级别为14的应用程序.我认为所有兼容设备都应该安装Roboto字体作为默认设置吗?如果我将textView字体设置为Roboto或Roboto Light,它似乎默认为普通的sans字体.

有没有办法使用Roboto而不包括Roboto字体作为资产?

Ahm*_*mad 58

有没有办法使用Roboto而不包括Roboto字体作为资产?

对于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);
        }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在Layouts中使用它,如下所示:

<com.my.package.TextView_Roboto>
  android:layout_width="..."
  android:layout_height="..."
  [...]
</com.my.package.TextView_Roboto>
Run Code Online (Sandbox Code Playgroud)

当然,您可以创建TextView布局.一个用于Pre HC,一个用于HC及以上(您必须使用布局和layout-v11文件夹).现在,您可以使用<include>标记在Layout中包含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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

您可以使用Android 4.1+中的Roboto,如下所示:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
Run Code Online (Sandbox Code Playgroud)

  • 三星手机是迄今为止最受欢迎的Android手机.虽然所有来自4.1及以上的三星手机都拥有Roboto,但他们也有一款名为Samsung Sans的东西,如果你的用户将其设置为默认字体,那么android:font-family请求所有人都返回Samsung Sans,而不是Roboto.如果你有固定的紧凑布局,没有无法伸展的蠕动空间,三星Sans将打破它们.听起来米洛发现了这个问题的一个变种.围绕这个没有简单的方法.如果您必须拥有Roboto,则必须将其打包为资产并将其明确设置为字体. (11认同)