Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 472
Anna Avatar asked May 10 '16 11:05

Anna


People also ask

Which attribute is used to show any text inside TextView?

We use attribute android: hint= "Text will show here", so if we will set the TextView in the MainActivity.

How do I access TextView?

Access TextView in Layout File from Kotlin To access the TextView present in a layout file, from Kotlin file, use findViewById() method with the TextView id passed as argument. The attribute id will help to find the specified widget. Following is a complete example to access the TextView present in layout file.


1 Answers

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());
like image 79
Sevle Avatar answered Sep 29 '22 18:09

Sevle