How, using java, leave bold parts of a TextView?

1

I would like to know how to make a particular part of a text that will be displayed in a TEXTVIEW appear in bold:

Iwouldlikethedisplayedtexttolooklikethis:Totalvalue=>R$1100.

Activity:

package genesysgeneration.stackall;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tvValor;
    private Button btnMais100;
    int valor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvValor=(TextView)findViewById(R.id.tvValor);
        btnMais100=(Button)findViewById(R.id.btnMais100);
        valor=0;

        btnMais100.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                valor+=100;
                tvValor.setText(String.valueOf("Valor total => R$ " + valor + "."));

            }
        });

    }
}

I know I could create another TextView, but it does not suit me. I also know that I could do this in the TextView .xml, but it's not feasible because the text is dynamic (not so much in the example, but in my real project where I want to use it).

    
asked by anonymous 11.02.2017 / 21:51

1 answer

1

Use the class SpannableString , it allows you to attach markup objects > to specific parts of a text.

TextView textView = (TextView)findViewById(R.id.textView);
String label = "Valor total => ";
String valor = "R$ 1100";

SpannableString textoNegrito = new SpannableString(label + valor);
textoNegrito.setSpan(new StyleSpan(Typeface.BOLD), label.length(), textoNegrito.length(), 0);
textView.setText(textoNegrito);
    
11.02.2017 / 23:29