사용자 정의 TextView
이 있고 내 서버의 모든 텍스트를 가져와 어떤 스타일이 올지 모릅니다. 예를 들어, bold
, italic
및 Textstyles
을 포함 할 수 있습니다. 하지만 정말 런타임을 처리하는 방법을 모르겠다. 런타임시 Textview의 서체 변경
assets
폴더 생성 :
을 그리고 내 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 모자 어떻게 작동, 어떤 아이디어가 이것을 달성하는 방법? 감사합니다.
처럼 호출 할 수 있습니다? – Blackbelt
감사합니다. 나는 그것을 더했습니다! – Davis
괜찮아 보입니다. 그게 무슨 문제 야? – Blackbelt