Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

android - How to get the fontFamily name from 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!" />

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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.

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:

In 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"
/>

In res/values/strings.xml:

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

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...