如何通过XML设置Android字体类型

3
Typeface fontRobo = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Black.ttf");
viewTotalValue.setText(total.toString());

2
很遗憾,这是不可能的。 - A.S.
可能是重复的问题:在Android中从XML文件访问assets文件夹下的字体 - Siruk Viktor
1
如果您不想为每个TextView都执行此操作,可以创建一个扩展TextView的类,并在其中设置您的Typeface。然后,您可以在xml文件中使用该类,例如com.your.customview.package.CustomFontTextView - vilpe89
3个回答

19
你可以通过重写 TextView 来创建自己的 TextView,像这样:

你可以通过重写 TextView 来创建自己的 TextView,像这样:

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setType(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setType(context);
    }

    public MyTextView(Context context) {
        super(context);
        setType(context);
    }

    private void setType(Context context){
        this.setTypeface(Typeface.createFromAsset(context.getAssets(),
                    "foo.ttf"));

        this.setShadowLayer(1.5f, 5, 5, getContext().getResources().getColor(R.color.black_shadow));
    }
}

并像这样使用:

<com.your.project.package.MyTextView
        android:id="@+id/oppinfo_mtv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"  
        android:text="Player 1"
        />

1
向他展示如何在XML文件中使用它的示例 :) - vilpe89
你太快了!回答很好。 - vilpe89
1
非常感谢!清晰易懂! - KinGPinG

3
你可以创建一个自定义类,继承TextView,比如说FontTextView
为该类定义一个特殊的字符串属性,比如说"font"。
然后,在你的FontTextView构造函数中,根据font属性的值,从你的资源中选择适当的Typeface
参见:

3

仅仅为了设置字体而扩展TextView看起来过于昂贵且不好。最清晰的方法是使用Android Data-Binding Framework和BindingAdapter:

@BindingAdapter("bind:font")
public static void setTypeface(TextView textView, int index) {
    Typeface myTypeface = //retrieve typeface from cache, based on some font index
    textView.setTypeface(myTypeface);
}

XML中的声明:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:font="@{R.attr.Proxima_Nova_Regular}" 
/>

attrs.xml:

<attr name="Proxima_Nova_Regular"/>
<attr name="Proxima_Nova_Black"/>    
<attr name="Proxima_Nova_Bold"/>

或者以相同的方式使用资源整数 在您的缓存/创建辅助程序中确定R.attr.您的字体和类型面之间的依赖关系。

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