Java – Get the custom properties of a custom TextView from XML

Get the custom properties of a custom TextView from XML… here is a solution to the problem.

Get the custom properties of a custom TextView from XML

How to get the custom

fontname property of a custom TextView to set the font to the Textview.
Set the font in the TextView based on the property value

public class MyTextView extends TextView
{
    public MyTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

public MyTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

public MyTextView(Context context)
    {
        super(context);
        init();
    }

public void init()
    {
           set font_name based on attribute value of textview in xml file
          String font_name = "";
        if (!isInEditMode())
        {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                    "fonts/"+font_name);
            setTypeface(tf);
        }
    }

In an XML file

<com. Example.MyTextView 
            android:id="@+id/header"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            fontname="font.ttf"
            android:text="Header"   
/>

I also put font.ttf files in assets->fonts
Thanks

Solution

1 。 Add the readAttr(context,attrs) method to your constructor, as shown below.

public MyTextView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    readAttr(context,attrs);
    init();
}

public MyTextView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    readAttr(context,attrs)
    init();
}

public MyTextView(Context context)
{
    super(context);
    init();
}

2。 Define the readAttr() method in the same class.

private void readAttr(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);

 Read the title and set it if any
    String fontName = a.getString(R.styleable.MyTextView_fontname) ;
    if (fontName != null) {
         We have a attribute value and set it to proper value as you want
    }

a.recycle();
}

3。 Modify the attrs.xml file (res/values/attrs.xml) and add the following to the file

<declare-styleable name="MyTextView">
  <attr name="fontname" format="string" />
</declare-styleable>

4。 In an XML file.

<com. Example.MyTextView 
   android:id="@+id/header"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   custom:fontname="font.ttf"
   android:text="Header" />

5。 Add this line to the top container of the XML file.

xmlns:custom="http://schemas.android.com/apk/res/com.yourpackage.name"

That’s all

Related Problems and Solutions