Change the font through xml

0

I have the sources of my application in:

  

main > assets > fonts

Is there any way to pass directly in xml? (% with%)

Or just via Java?

    
asked by anonymous 04.06.2016 / 23:37

1 answer

1

Thiago,

Your question is quite interesting. The solution I have always used is the one that follows in my answer. Even to this day I found no other and would like to simply do it for XML, it would be so much easier !!! If you find a better way, tell us! : -)

You can define a TextView specialization and apply the font you need. The class below can do this for you, however it is important to say that you leave this class a bit more flexible, to reuse it in other projects, working better the setFont method.

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class ThiagoLuizTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
        setFont();
    }
    public ThiagoLuizTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setFont();
    }
    public ThiagoLuizTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFont();
    }

    private void setFont() {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/RobotNew.ttf");
        setTypeface(font, Typeface.NORMAL);
    }
}

To use in XML, an example follows: (Of course it will depend on where your class is located in the structure of your project, so com.project.ui should be substituted for your package structure)

  • I tried to use a library called Caligraphy but the performance was very poor in code profiling. Use reflection for some things and I did not like it. I did it my way again. In cases of using your custom textview, remember to adopt the default viewholder correctly in lists so you do not have problems.

I hope to have helped and a hug,

    
05.06.2016 / 03:34