user3553099
user3553099

Reputation: 11

Android : Proper way to use custom typeface in

What is the right way to use typeface in Android? I see many examples using custom XML tag for text view. I tried to to set in Java to normal text view and it works fine, so what is the reason to use custom fields?

Upvotes: 1

Views: 376

Answers (1)

kandroidj
kandroidj

Reputation: 13932

When using a custom Typeface its best to add the Typeface to your /assets directory in your project. It is fairly lightweight to do the following:

TextView customTypefaceTextView = (TextView) findViewById(R.id.customTypefaceTextView);
Typeface customTypeface = Typeface.createFromAsset(getAssets(), "Custom_Typeface.ttf");
customTypefaceTextView.setTypeface(customTypeface);

Just remember that finding your assets will be related to the current Context so if your using custom fonts in a Fragment vs. Activity you will want to call getActivity().getAssets() instead of just getAssets().

This is a reference to the quick tip from : http://code.tutsplus.com/tutorials/customize-android-fonts--mobile-1601

Additionally it may be more practical to create a class that extends TextView to help you have a more practical implementation to a custom Font that can be used for the TextViews you want to add a custom font to like so:

public class CustomTitleTextView extends TextView {

private Context m_classContext          = null;
private Typeface m_customTypeFace       = null;

    // Default Constructor
public CustomTitleTextView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    this.m_classContext = context;
    createRobotoTitleTextView();
}

    // Default Constructor
public CustomTitleTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
    this.m_classContext = context;
    createRobotoTitleTextView();
}

    // Default Constructor
public CustomTitleTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
    this.m_classContext = context;
    createRobotoTitleTextView();
}

    // Adds the Typeface to the TextView
private void createRobotoTitleTextView()
{
    m_customTypeFace = Typeface.createFromAsset(m_classContext.getAssets(), "Roboto-Thin.ttf");
    this.setTypeface(m_customTypeFace);

}


}

And then you can use this in XML in any layout

<packagename.CustomTitleTextView
  android:id="@+id/customTitleTextView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

Update

These are a few ways that I have had success implementing custom fonts. The sample showing how to add a custom TextView via extends TextView then adding it in XML is not necessary it just provides a skeleton of how to create your TextView as a re-useable object rather than doing it dynamically in your Activity or Fragment.

Good luck!

Upvotes: 1

Related Questions