2

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.

Ajay Sivan
  • 2,807
  • 2
  • 32
  • 57
  • See this : [How to change a TextView's style at runtime](http://stackoverflow.com/questions/4630440/how-to-change-a-textviews-style-at-runtime) – FarshidABZ Feb 02 '17 at 14:21

1 Answers1

5

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*/);
            }
      }
 }
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62