Android TextView与多种字体(语言)一起使用



我有一个预加载了一些内容的文本视图。我想要的是用英语显示内容的某些部分。举个例子,我有三个英文段落,然后每个段落后面都要跟着中文段落。我不能使用内容的跨度,因为长度不同。请为我提供解决方案或更好的替代方案。

感谢:)

您可以用HTML的方式格式化它,如下所示:

MyTypeFace.class

package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;
public class MyTypeFace extends TypefaceSpan {
private final Typeface newType;
public MyTypeFace(String family, Typeface type) {
    super(family);
    newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
    applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
    applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
    int oldStyle;
    Typeface old = paint.getTypeface();
    if (old == null) {
        oldStyle = 0;
    } else {
        oldStyle = old.getStyle();
    }
    int fake = oldStyle & ~tf.getStyle();
    if ((fake & Typeface.BOLD) != 0) {
        paint.setFakeBoldText(true);
    }
    if ((fake & Typeface.ITALIC) != 0) {
        paint.setTextSkewX(-0.25f);
    }
    paint.setTypeface(tf);
}
}  

现在,只需继续从String.xml中获取故事,在它们上应用字体,然后显示它们。

String text1=findViewById(R.string.text1);  
String text2=findViewById(R.string.text2);  
TextView textView = (TextView) findViewById(R.id.custom_fonts);  
txt.setTextSize(30);
Typeface font1 = Typeface.createFromAsset(getAssets(), "english.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "chinese.ttf");   
text1.setSpan (new MyTypeFace("", font1), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
text2.setSpan (new MyTypeFace("", font2), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
String totalText=text1+"<br>"+text2;  
textView.setText(Html.fromHtml(totalText));

您可以尝试从以下示例中找到答案:

TextView text = new TextView(context);
text.setText(Html.fromHtml("<b>" + "some text" + "</b>" +  "<br />" + 
            "<small>" + "some text" + "</small>" + "<br />" + 
            "<small>" + "some text" + "</small>"));

最新更新