如何从 TextView 获取 fontFamily 名称?

How to get the fontFamily name from TextView?

我想从代码中的 xml 获取字体系列名称属性名称。 例如我有自定义 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"。 这个有可能?以及如何做到这一点?谢谢

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

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

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

在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:

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

然后您可以通过 android:tag 字段访问字体系列名称:

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