【问题标题】:how to set Android Typeface from xml如何从 xml 设置 Android 字体
【发布时间】:2014-03-27 13:55:45
【问题描述】:
Typeface fontRobo = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Black.ttf");
viewTotalValue.setText(total.toString());

【问题讨论】:

  • 很遗憾这是不可能的
  • 如果您不想对每个 TextView 都这样做,您可以创建扩展 TextView 的类并在其中设置您的字体。然后您可以在您的 xml 文件中使用该类,例如 com.your.customview.package.CustomFontTextView.

标签: android android-typeface


【解决方案1】:

仅仅为了设置字体而扩展 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.您的字体和字体实例之间的依赖关系。

【讨论】:

    【解决方案2】:

    您可以通过像这样覆盖 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"
            />
    

    【讨论】:

    • 向他展示如何在 xml 文件中使用它的示例:)
    • 你太快了!不错的答案
    • 非常感谢!清晰易懂!
    【解决方案3】:

    您可以创建一个扩展 TextView 的自定义类,比如说 FontTextView

    为该类定义一个特殊的字符串属性,比如说“字体”。

    然后,在您的FontTextView 构造函数中,根据font 属性的值,从您的资产中选择适当的Typeface

    见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 2017-10-04
      • 1970-01-01
      • 2012-01-24
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多