Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a custom attribute of custom textview from XML

How to get custom fontname Attributes of Custom TextView for Set font to Textview. Based on Attributes value set Font in TextView

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 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 file in assets->fonts Thank You

like image 516
Dedaniya HirenKumar Avatar asked Dec 25 '22 05:12

Dedaniya HirenKumar


1 Answers

1 . Add readAttr(context,attrs) method to your constructor like 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 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 attrs.xml file (res/values/attrs.xml) and add the below to the file

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

4 . In 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 xml file.

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

Thats all

like image 86
Rohit Sharma Avatar answered Dec 28 '22 06:12

Rohit Sharma