Bold in a part of a TextView

10

Good, I wanted to know if in a TextView you could put only a part of it in bold, like for example:

Hello world , my name is Pepe .

    
asked by borjis 17.11.2016 в 16:48
source

5 answers

10

There are several ways to do this (two are similar to this answer but now you would use <b> ).

One option is loading the text from the text from Strings.xml and using Html.fromHtml() , in this case it is very important to use CDATA ,

<string name="mi_mensaje"><![CDATA[Hola <b>mundo</b>, me llamo <b>Pepe</b>]]></string>

and loading the text to TextView with:

textView.setText(Html.fromHtml(getResources().getString(R.string.mi_mensaje)));

You can also load the text without using CATA , for this case you use the method getText () , we define the chain in Strings.xml in this way:

<string name="mi_mensaje">Hola <b>mundo</b>, me llamo <b>Pepe</b></string>

and we load it using the method getText () :

textView.setText(getText(R.string.mi_mensaje));

Another option is to write directly within the textView your text and apply the transformation Html :

textView.setText(Html.fromHtml("Hola <b>mundo</b>, me llamo <b>Pepe</b>"));

The third option is using SpannableString and defining an StyleSpan with style bold for words in bold, in this option you have to calculate the start and end index of the or the words to which you want to apply the style:

   TextView textView = (TextView) findViewById(R.id.textView);
    SpannableString miTexto = new SpannableString("Hola mundo, me llamo Pepe");
    StyleSpan boldSpan1 = new StyleSpan(Typeface.BOLD);
    StyleSpan boldSpan2 = new StyleSpan(Typeface.BOLD);
    miTexto.setSpan(boldSpan1, 5, 10, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    miTexto.setSpan(boldSpan2, 20, miTexto.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(miTexto);

getting the same result with the 3 options:

Using a .xml or a .json you can add html code and parse the value to be represented in your view, in the case of an xml do not forget to add the container <![CDATA

Using an XML

<texto><![CDATA[Hola <b>mundo</b>, me llamo <b>Pepe</b>]]></texto>

Using a .json

{
    "texto": "Hola <b>mundo</b>, me llamo <b>Pepe</b>", 
}
    
answered by 17.11.2016 / 16:52
source
2

You can make use of the Html object and its fromHtml method to give bold to the necessary words in your string

yourTextView.setText(Html.fromHtml("Hola <b>mundo</b>, me llamo <b>Pepe</b>."));
    
answered by 17.11.2016 в 16:53
2

Well, I see that all the answers they provide you is making use of HTML which are very good choice, in this answer I propose you to use SpannableStringBuilder in case you want to apply it someday otherwise: D

final SpannableStringBuilder texto= new SpannableStringBuilder("Tu texto");

final StyleSpan letraEnNegrita= new StyleSpan(android.graphics.Typeface.BOLD); // Para hacer negrita

texto.setSpan(letraEnNegrita, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // Convierte los primeros 4 caracteres en negrita, tu puedes decirle cuantos caracteres :)
tuTextview.setText(texto);
    
answered by 17.11.2016 в 17:12
2

Taste my class, extend TextView by allowing HTML and the fade-in-out effect to be added when changing the value of the text:

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by efraespada on 15/04/2016.
 */
public class SuperTextView extends TextView {

    private boolean ready;
    private int finalOpacity;

    public SuperTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);

        ready = false;
        finalOpacity = 255;
        addTextChangedListener(new CustomTextWatcher(this));
    }

    public SuperTextView(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ready = false;
        finalOpacity = 255;
        addTextChangedListener(new CustomTextWatcher(this));
    }

    public SuperTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ready = false;
        finalOpacity = 255;
        addTextChangedListener(new CustomTextWatcher(this));
    }

    public SuperTextView(Context context) {
        super(context);
        ready = false;
        finalOpacity = 255;
        addTextChangedListener(new CustomTextWatcher(this));
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (ready && getText() != null && text != null) {
            String toChange = (String) text.toString();
            String myText = "" + getText();

            if (!myText.equals(Html.fromHtml(toChange).toString()))
                super.setText((CharSequence) Html.fromHtml(toChange), type);
        } else {

            String r;

            try {
                r = Html.fromHtml((String) text).toString();
            } catch (ClassCastException e) {
                e.printStackTrace();
                r = text.toString();
            }

            CharSequence t = (CharSequence) r;

            super.setText(t, type);
        }
    }

    public void setText(CharSequence text, int opacity) {
        if (opacity >= 0 && opacity <= 255) finalOpacity = opacity;

        if (ready && getText() != null && text != null) {
            String toChange = (String) text.toString();
            String myText = "" + getText();
            CharSequence t = (CharSequence) Html.fromHtml(toChange);
            if (!myText.equals(Html.fromHtml(toChange).toString())) super.setText((CharSequence) Html.fromHtml(toChange), null);
        } else super.setText((CharSequence) Html.fromHtml((String) text), null);
    }

    public class CustomTextWatcher implements TextWatcher {

        private TextView element;
        private Integer[] rgb;

        public CustomTextWatcher(TextView element) {
            this.element = element;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            final int from = getAlpha(element.getCurrentTextColor()), to = 0;

            ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   // animate from 0 to 1
            anim.setDuration(600);                              // for 300 ms

            rgb = parseColor(element.getCurrentTextColor());
            final int[] alpha  = new int[1];                  // transition color
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    alpha[0] = (int) (from + (to - from)*animation.getAnimatedFraction());
                    element.setTextColor(Color.argb(alpha[0], rgb[0], rgb[1], rgb[2]));
                }
            });

            anim.start();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Log.e("Text","change:" + getCurrentTextColor());
        }

        @Override
        public void afterTextChanged(Editable s) {
            ready = true;
            final int from = 0, to = finalOpacity;

            ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   // animate from 0 to 1
            anim.setDuration(600);                              // for 300 ms

            final int[] alpha  = new int[1];                  // transition color
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    alpha[0] = (int) (from + (to - from)*animation.getAnimatedFraction());
                    element.setTextColor(Color.argb(alpha[0], rgb[0], rgb[1], rgb[2]));
                }


            });

            anim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    finalOpacity = 255;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    finalOpacity = 255;
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                    finalOpacity = 255;
                }
            });

            anim.start();
        }

        public Integer[] parseColor(int value) {
            Integer[] rgb = new Integer[3];

            String hexColor = String.format("%06X", (0xFFFFFF & value));

            int color = (int)Long.parseLong(hexColor, 16);
            rgb[0] = (color >> 16) & 0xFF;
            rgb[1] = (color >> 8) & 0xFF;
            rgb[2] = (color >> 0) & 0xFF;

            return rgb;
        }

        public int getAlpha(int value) {
            return new ColorDrawable(value).getAlpha();
        }
    }
}

To add it to your XML:

<com.example.SuperTextView
            android:id="@+id/text"
            style="@android:style/Widget.Holo.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text=""
            android:textColor="@color/colorAccent" />

Programmatically add text to the object.

    
answered by 17.11.2016 в 17:58
1

You can use HTML tags for this purpose. For example, you can perform:

String tuString = "Hola <b>mundo</b>, me llamo <b>Pepe</b">; 
tuTextView.setText(Html.fromHtml(tuString));
    
answered by 17.11.2016 в 16:52