将特定字体设置为我的应用

时间:2017-11-07 10:54:54

标签: java android fonts

为了将字体设置为android app,我使用以下函数:

public static void persianizer(ViewGroup viewGroup) {

    int childCount = viewGroup.getChildCount();

    for (int i = 0; i < childCount; i++) {
        View child = viewGroup.getChildAt(i);

        if (child instanceof ViewGroup) {
            persianizer((ViewGroup) child);
            continue;
        }

        if (child instanceof TextView) {
            ((TextView) child).setTypeface(RootApp.typeface);
        }

    }

}

它获取布局的根视图,然后为该布局的每个textview子项设置类型face。但我认为这不是一个好的解决方案。

更改整个应用程序字体的最佳做法是什么?

2 个答案:

答案 0 :(得分:2)

您可以创建自己的字体TextView类,它将扩展TextView并根据您的需要发送字体,看看:

public class TypefacedTextView extends TextView {

public TypefacedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedButton);
    // String fontName = styledAttrs.getString(R.styleable.TypefacedButton_font);
    styledAttrs.recycle();

    Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" +getResources().getString(R.string.roboto_light));
    setTypeface(typeface);

}

将您的字体文件保存在资产文件夹中,然后逐个调用Typeface.createFromAsset()

这是xml中的T​​ypeFaceTextview:

     <com.demo.TypefacedTextView 
      android:id="@+id/textview"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:ems="10"       
      </com.demo.TypefacedTextView >

快乐的编码!!

答案 1 :(得分:0)

试试这个

public class CustomTextView extends android.support.v7.widget.AppCompatTextView {

public CustomTextView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    init();
}

public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CustomTextView(Context context) {
    super(context);
    init();
}

private void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
            "Walkway Black.ttf");
    setTypeface(tf);
}

}

然后在您的布局中使用此CustomText视图,如:

 <app.com.demo.CustomTextView
    android:id="@+id/tv_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="@dimen/_10dp"
    android:inputType=""
    android:text="@string/name"
    android:textColor="@color/colorSkyBlue"
    android:textSize="20sp"
    android:textStyle="bold" />