Ajay Sivan
Ajay Sivan

Reputation: 2989

Custom TextView with Bold, Normal & Italic Styles

I am trying to create a TextView with custom font-family. I have Created one which supports the normal font. But I am unable to implement bold/italic styling on the custom TextView.

This is my Custom TextView Class

public class KTextView extends TextView {

    public KTextView(Context context) {
        super(context);
        TypefaceHelper.setTypeface(context, this);
    }

    public KTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypefaceHelper.setTypeface(context, this);
    }

    public KTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypefaceHelper.setTypeface(context, this);
    }

}

This is the TypefaceHelper Class

public class TypefaceHelper {
private static final String FONT = "AvenirNext-Regular.otf";

private static Typeface typeface = null;

public static void setTypeface(Context context, TextView textView) {
    if (typeface == null) {
        typeface = Typeface.createFromAsset(context.getAssets(), FONT);
    }
    textView.setTypeface(typeface);
}

Can anyone suggest a way to implement Bold and Italic Styling.

Upvotes: 2

Views: 1252

Answers (1)

rafsanahmad007
rafsanahmad007

Reputation: 23881

try this:

textview.setTypeface(typeface, Typeface.BOLD);

you can use also ITALIC and BOLD_ITALIC

for custom textview use:

 public class MyTextView extends TextView {

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

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

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


     public void setTypeface(Typeface tf, int style) {
           if (style == Typeface.BOLD) {
                super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/fonts_name")/*, -1*/);
            } else {
               super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/fonts_name")/*, -1*/);
            }
      }
 }

Upvotes: 5

Related Questions