Применить два разных стиля шрифта к TextView - PullRequest
28 голосов
/ 08 марта 2012

Я хочу применить два разных стиля шрифта к тексту в одном TextView.

Мой случай такой же, как у Android - два предложения, два стиля, один TextView . Разница лишь в том, что я хочу установить пользовательский шрифт для всего текста. Я включил Helvetica Font в качестве активов в свой проект и хочу применить этот шрифт к TextView, первая часть текста будет Helvetica BOLD, а оставшаяся часть Helvetica NORMAL. Любые предложения, как это можно сделать?

Текст необходим в следующем формате. Пользовательский текст с разными стилями и одним текстом.

enter image description here

Ответы [ 5 ]

74 голосов
/ 08 марта 2012

Один из способов сделать это - расширить TypefaceSpan :

import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

    public class CustomTypefaceSpan extends TypefaceSpan {
        private final Typeface newType;

        public CustomTypefaceSpan(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 firstWord = "first ";
String secondWord = "second";

// Create a new spannable with the two strings
Spannable spannable = new SpannableString(firstWord+secondWord);

// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE), firstWord.length(), firstWord.length() + secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the text of a textView with the spannable object
textView.setText( spannable );
3 голосов
/ 22 января 2016

Вот решение более простое, вы можете использовать HTML для установки разных стилей на один и тот же TextView.

Например:

// Styled label
String styledText = "<big><b><font color='#333333'>title</font></b></big> <small><b><font color='#CC5490'>subtitle</font></b></small>";

// Apply the styled label on the TextView
textView.setText(Html.fromHtml(styledText));

Вам необходим следующий импорт:

import android.text.Html;
2 голосов
/ 08 марта 2012

Это может сработать - создайте свой собственный TextView, а затем используйте StyleSpan на одной его части:

public class CustomTextView extends TextView {

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

    @Override
    public void setTypeface(Typeface tf, int style) {
        if (style == 1){
            //replace "HelveticaBOLD.otf" with the name of your bold font
            tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "HelveticaBOLD.otf");
        }else{
            //replace "HelveticaNORMAL.otf" with the name of your normal font
            tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "HelveticaNORMAL.otf");
        }
        super.setTypeface(tf, 0);
    }
}

И тогда вы можете сделать что-то вроде:

int index1 = 0; //wherever bold should begin
int index2 = 5; //wherever bold should end

Spannable span = new SpannableString("some string");
span.setSpan(new StyleSpan(Typeface.BOLD),index1, index2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

((CustomTextView)findViewById(R.id.yourTextView)).setText(span);
0 голосов
/ 08 марта 2012

Вы можете создать собственный вид и визуализировать ваш текст с помощью двух Paint объектов, используя canvas.drawText method

0 голосов
/ 08 марта 2012

пытались ли вы установить пользовательский шрифт в TextView перед применением разбираемого текста?

Typeface face = Typeface.createFromAsset(ctx.getAssets(), "fonts/boost.ttf")
TextView tv = (TextView) ctx.findViewById(id);
tv.setTypeface(face);

и затем примените SpannableStringBuilder, как в связанном вопросе - я только предполагаю, что если ваш ttf поддерживает 'normal' и 'bold', он будет соответственно отображаться

...