如何从 TextView 获取 fontFamily 名称? [英] How to get the fontFamily name from TextView?

查看:57
本文介绍了如何从 TextView 获取 fontFamily 名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从代码中的 xml 中获取字体系列名称 attr 名称.例如我有自定义 textView 类:

I want to get the font family name attr name from the xml in code. For example i have custom textView class:

public class TextVieww extends TextView{

    public TextVieww(Context context) {
        super(context);
    }
    public TextVieww(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextVieww(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void init(Context mContext ,TextView view) {
    }
}

XML:

 <com.typefacetest.TextVieww
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textStyle="bold"
        android:fontFamily="sans-serif-thin"
        android:text="Hello World!" />

我想从 textView.class 中获得sans-serif-thin".这个有可能?以及如何做到这一点?谢谢

i want to get the "sans-serif-thin" from the textView.class. This is possible? and how to do this? thank's

推荐答案

如果在 XML 中定义字体系列名称,则无法以编程方式获取它,因为在 XML 中定义时,它会在编译时映射到关联的本机字体系列,并且无法收回,没有一些丑陋的反映(我会尝试为上述声明找到一个完整答案的来源,Typeface 的文档似乎是有限的).

You cannot get the font family name programmatically if it's defined in XML because when defined in XML it's mapped in compile time to the associated native font family and cannot be retracted, without some ugly reflection (I'll try to find a source for the above claim for a complete answer, the documentation for Typeface seems to be limited).

正如@Ashwini 的评论中提到的,您始终可以在资产文件夹下使用自定义字体,并且能够在 XML 文件和 .java 中看到它.

As mentioned in comments by @Ashwini you can always use a custom font under the assets folder and be able to see it in both the XML file and .java.

或者,如果你想使用原生字体系列,你可以做一些更简单但有点不优雅的事情;使用 TextView 的 android:tag 字段来存储字体族名:

Alternatively, if you want to use a native font family you can do something simpler and a bit inelegant; use the android:tag field of TextView to store the font family name:

在 XML 中:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:id='@+id/textView'
    android:textSize="30sp"
    android:textStyle="bold"
    android:fontFamily="@string/myFontFamily"
    android:tag="@string/myFontFamily"
/>

在 res/values/strings.xml:

In res/values/strings.xml:

<resources>
    ...
    <string name="myFontFamily">sans-serif-thin</string>
    ...
</resources>

然后就可以通过 android:tag 字段访问字体族名了:

Then you can access the font family name through the android:tag field:

TextView textView = (TextView) findViewById(R.id.textView);
String fontFamily = String.valueOf(textView.getTag());

这篇关于如何从 TextView 获取 fontFamily 名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆