簡體   English   中英

如何在Android的TextView中使用`Open Sans`字體樣式?

[英]How to use `Open Sans` font style for textview in android?

如何在Android中為Textview使用Open Sans字體樣式? 默認情況下,字體家族中的Open Sans不可用。

使用此lib更改Hole應用程序書法上的字體

使用此代碼來更改文字字體。

將字體文件放在資產文件夾中。 就我而言,我創建了一個名為fonts的子目錄。

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

Android O和Android支持庫26添加了對可下載字體的支持。

Google字體在Google Play服務中提供了字體提供程序。

請閱讀官方文檔: https : //developers.google.com/fonts/docs/android

在此處輸入圖片說明

第1步:創建一個assest文件夾-> fonts文件夾->放置.ttf文件。

第2步:創建您的自定義textview類,如下所示:

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();
        }
    }
  }

步驟4:在create方法的應用程序類中編寫代碼行。 將“ serif”字體替換為您的字體家族

FontsOverride.setDefaultFont(this, "SERIF", "fonts/Lato-Regular.ttf");

步驟5:如何使用如下所示的自定義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"/>

您可以檢查答案https://stackoverflow.com/a/3651168/6792992您可以按照與建議答案相同的方式使用任何一種字體

您必須添加自定義字體。 首先下載字體檔案的.ttf而你的情況,可以發現: https://www.fontsquirrel.com/fonts/open-sans一旦你擁有了它,我建議您在本教程中添加自定義字體: https://開頭futurestud .io / tutorials / custom-fonts-on-android-using-font-styles

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM