具有粗体、正常和斜体样式的自定义 TextView

Aja*_*van 2 android textview

我正在尝试创建一个TextView带有自定义字体系列的字体。我已经创建了一个支持普通字体的字体。但我无法在自定义上实现粗体/斜体TextView样式。

这是我的自定义TextView课程

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

这是TypefaceHelper班级

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);
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议一种实现粗体和斜体样式的方法。

raf*_*007 5

尝试这个:

textview.setTypeface(typeface, Typeface.BOLD);
Run Code Online (Sandbox Code Playgroud)

你也可以使用ITALICBOLD_ITALIC

对于自定义文本视图使用:

 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*/);
            }
      }
 }
Run Code Online (Sandbox Code Playgroud)