2016-08-03 7 views
1

사용자 정의 TextView이 있고 내 서버의 모든 텍스트를 가져와 어떤 스타일이 올지 모릅니다. 예를 들어, bold, italicTextstyles을 포함 할 수 있습니다. 하지만 정말 런타임을 처리하는 방법을 모르겠다. 런타임시 Textview의 서체 변경

나는 내가 사용하고 싶습니다 내 모든 글꼴과 assets 폴더 생성 :

enter image description here

을 그리고 내 CustomTextView에 나는이 같은 시도 :

public class CustomTextView extends TextView { 

private static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android"; 

public CustomTextView(Context context) { 
    super(context); 

    applyCustomFont(context, null); 
} 

public CustomTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    applyCustomFont(context, attrs); 
} 

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

    applyCustomFont(context, attrs); 
} 

private void applyCustomFont(Context context, AttributeSet attrs) { 

    //Workaround for Preview Mode 
    if (!isInEditMode()) { 
     int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL); 

     Typeface customFont = selectTypeface(context, textStyle); 
     setTypeface(customFont); 

    } else { 

     this.setTypeface(null, Typeface.NORMAL); 
    } 
} 

private Typeface selectTypeface(Context context, int textStyle) { 

    switch (textStyle) { 
     case Typeface.BOLD: // bold 
      return FontCache.getTypeface("fonts/OpenSans-Bold.ttf", context); 

     case Typeface.ITALIC: // italic 
      return FontCache.getTypeface("fonts/OpenSans-Italic.ttf", context); 

     default: 
      return FontCache.getTypeface("fonts/OpenSans-Regular.ttf", context); 
    } 
} 

} 

이 내 FontCache 클래스입니다 :

public class FontCache { 

//This caches the fonts while minimizing the number of accesses to the assets 

private static final HashMap<String, Typeface> fontCache = new HashMap<>(); 

public static Typeface getTypeface(String fontname, Context context) 
{ 
    Typeface typeface = fontCache.get(fontname); 

    if (typeface == null) 
    { 
     try { 
      typeface = Typeface.createFromAsset(context.getAssets(), fontname); 

     } catch (Exception e) { 
      return null; 
     } 

     fontCache.put(fontname, typeface); 
    } 

    return typeface; 
} 

} 

그러나 t 모자 어떻게 작동, 어떤 아이디어가 이것을 달성하는 방법? 감사합니다.

+1

처럼 호출 할 수 있습니다? – Blackbelt

+0

감사합니다. 나는 그것을 더했습니다! – Davis

+0

괜찮아 보입니다. 그게 무슨 문제 야? – Blackbelt

답변

1

당신은 setTypeface(Typeface tf, int style)

@Override 
public void setTypeface(Typeface tf, int style) { 
    Typeface customFont = selectTypeface(context, textStyle) 
    super.setTypeface(customFont, style); 
} 

을 무시할 수 있고`FontCache` 무엇을 외부에서 당신은

mTextView.setTypeface(null, Typeface.BOLD); 
+0

도움이 되셨습니다. 감사합니다. – Davis

+0

당신은 환영합니다 – Blackbelt