如何从TextView获取fontFamily名称

如何从TextView获取fontFamily名称

本文介绍了如何从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在评论中提到的那样,您始终可以在Assets文件夹下使用自定义字体,并且能够在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名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:21