Change the source via xml

Asked

Viewed 198 times

0

I have the sources of my app on :

main > Assets >fonts

Is there any way to pass directly into xml? (android:typeface="")

Or just via Java ?

1 answer

1


Thiago,

Your question is quite interesting. The solution I have always used is the one that follows in my answer. Even today I did not find another and I would just like to do also by XML, it would be so much easier!!! If you discover some better way, tell us! :-)

You can define a Textview specialization and apply the font you need. The class below can do this for you, but it is important to say that make this class a little 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, here is an example: (Of course it will depend on where your class is located in the structure of your project, so with.projecto.ui it must be replaced for its package structure)

  • I tried to use a library called Caligraphy but the performance was terrible in code Profiling. It uses reflection for some things and I didn’t like it. I did it again anyway. In cases of using your custom textview, remember to adopt the viewholder pattern correctly in lists to have no problems.

I hope I helped and a hug,

  • I liked your answer! It’s a great alternative! Much less laborious!

  • @Thiagoluizdomacoski cool! Good that helped! A hug!

  • Dude, I won’t mark it right for a while (we hope someone knows how) because it’s about loading with XML! But it helped a lot!

  • @Thiagoluizdomacoski with all reason friend, as I answered myself, also I do not know if there is a solution that would be better even! In fact, if it exists, it will be very welcome and much better than I ever implemented and as I instructed you! Rest assured :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.