如何在Android的TextView中使用Open Sans字体样式?

4

如何在Android的TextView中使用Open Sans字体样式?默认情况下,Open Sans字体系列不可用。

5个回答

5

3

使用这个库可以改变整个应用程序的字体 Calligraphy

使用此代码可以更改特定文本的字体。

将字体文件放置在资产文件夹中。在我的情况下,我创建了一个名为fonts的子目录。

    TextView tv = (TextView) findViewById(R.id.textViewName);
    Typeface face = Typeface.createFromAsset(getAssets(),"fonts/opansans.ttf");
    tv.setTypeface(face);

编辑已经修复了评论中的语法问题,为什么它们被撤销了? - Depau

1

enter image description here

步骤1:创建一个资源文件夹 -> 字体文件夹 -> 放置您的.ttf文件。 步骤2:创建您自己的自定义文本视图类,如下所示:
public class LotaRegularTextView extends TextView {

    public LotaRegularTextView(Context context) {
        super(context);
        this.setTypeface(Typeface.SERIF);
    }
    public LotaRegularTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTypeface(Typeface.SERIF);
    }
    public LotaRegularTextView(Context context, AttributeSet attrs, int 
           defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setTypeface(Typeface.SERIF);
    }
}

步骤 3:将FontsOverride.class添加到您的软件包中,此类将默认字体系列替换为您的字体系列。
  public final class FontsOverride {

    public static void setDefaultFont(Context context,
            String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    protected static void replaceFont(String staticTypefaceFieldName,
            final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
  }

步骤四:在应用程序类的创建方法中编写代码行。将“serif”字体替换为您的字体系列。
FontsOverride.setDefaultFont(this, "SERIF", "fonts/Lato-Regular.ttf");

第五步:如何使用自定义的TextView类,如下所示。
 <com.example.widget.LotaRegularTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/padding10"
        android:text="Ashish"
        android:textColor="@color/gini_gray_color_7d7d7d"
        android:textSize="@dimen/s_common_a"/>

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接