Definir a cor da extensão do TextView no Android


206

É possível definir a cor de apenas extensão de texto em um TextView?

Eu gostaria de fazer algo semelhante ao aplicativo do Twitter, no qual uma parte do texto é azul. Veja a imagem abaixo:

texto alternativo
(fonte: twimg.com )

Respostas:


430

Outra resposta seria muito semelhante, mas não precisaria definir o texto das TextViewduas vezes

TextView TV = (TextView)findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

mas como posso alterar a cor de várias palavras em todo o texto e não em uma extensão?
mostafa hashim

1
@mostafahashim cria vários intervalos repetindo a linha 3 wordtoSpan.setSpan (novo ForegroundColorSpan (Color.RED), 50, 80, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Ashraf Alshahawy

A solução Kotlin + Spannable String ficaria assim: stackoverflow.com/questions/4032676/…
Dmitrii Leonov

82

Aqui está uma pequena função de ajuda. Ótimo para quando você tem vários idiomas!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

38

Eu sempre acho exemplos visuais úteis ao tentar entender um novo conceito.

Cor de fundo

insira a descrição da imagem aqui

SpannableString spannableString = new SpannableString("Hello World!");
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Cor do primeiro plano

insira a descrição da imagem aqui

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Combinação

insira a descrição da imagem aqui

SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);

Um estudo mais aprofundado


30

Se você deseja mais controle, pode verificar a TextPaintturma. Aqui está como usá-lo:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

getColor (int id) foi descontinuado no Android 6.0 Marshmallow (API 23) stackoverflow.com/questions/31590714/…
Eka putra

Boa resposta com Click Listener.
Muhaiminur Rahman

20

Defina TextViewo texto do seu spannable e defina a ForegroundColorSpanpara o seu texto.

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

Obrigado! É possível fazer isso sem atribuir o texto ao TextView primeiro?
Hpique

Não me expliquei bem. Deixe-me reformular. As três primeiras linhas são necessárias? Você não pode criar o objeto Spannable diretamente da string?
Hpique

Não, você precisa armazenar o texto do seu TextView em um Buffer Spannable para alterar a cor do primeiro plano.
Jorgesys

Quero a mesma coisa com a cor e quero que tudo fique em negrito, exceto a parte colorida, a parte que quero ser em itálico, como posso fazer isso?
Lukap

1
como definir clique no intervalo?
Rishabh Srivastava

14

Outra maneira que pode ser usada em algumas situações é definir a cor do link nas propriedades da exibição que está usando o Spannable.

Se o seu Spannable for usado em um TextView, por exemplo, você poderá definir a cor do link no XML assim:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

Você também pode configurá-lo no código com:

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);

6

Existe uma fábrica para criar o Spannable e evitar o elenco, assim:

Spannable span = Spannable.Factory.getInstance().newSpannable("text");

1
Você poderia esclarecer como usar o SpannableFactory? Como deve ser o "texto"?
Piotr

depois de criar o Spannable pelo SpannableFactory, então como usá-lo?
MBH

6

Jogo de cor no texto pela passagem de Cordas e cor :

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

Defina o texto no TextView / Button / EditText etc chamando o código abaixo:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView);

Obter sequência colorida:

String name = getColoredSpanned("Hiren", "#800000");

Definir texto no TextView:

txtView.setText(Html.fromHtml(name));

Feito


5
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));

private SpannableString spannableString(String text, int start, int end) {
    SpannableString spannableString = new SpannableString(text);
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

Resultado:

insira a descrição da imagem aqui


você não gosta de Hasina
Abu

4

Apenas para adicionar à resposta aceita, como todas as respostas parecem falar android.graphics.Colorapenas: e se a cor que eu quero estiver definida res/values/colors.xml?

Por exemplo, considere as cores do Material Design definidas em colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_blue_500">#2196F3</color>
</resources>

( android_material_design_colours.xmlé seu melhor amigo)

Em seguida, use ContextCompat.getColor(getContext(), R.color.md_blue_500)onde você usaria Color.BLUE, para que:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

torna-se:

wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Onde eu achei isso:


3

Aqui está uma função de extensão Kotlin que eu tenho para isso

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

Use-o depois de definir seu texto para o TextView da seguinte maneira

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

1
  1. criar textview em seu layout
  2. cole esse código em sua MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily

1

Abaixo funciona perfeitamente para mim

    tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
    String originalText = (String)tvPrivacyPolicy.getText();
    int startPosition = 15;
    int endPosition = 31;

    SpannableString spannableStr = new SpannableString(originalText);
    UnderlineSpan underlineSpan = new UnderlineSpan();
    spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
    spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);

    spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    tvPrivacyPolicy.setText(spannableStr);

Saída para o código acima

insira a descrição da imagem aqui


1

Algumas respostas aqui não estão atualizadas. Porque, na maioria dos casos , você adiciona uma ação de clic personalizada ao seu link .

Além disso, conforme fornecido pela ajuda da documentação, a cor do link da sequência estendida terá uma cor padrão. "A cor padrão do link é a cor de destaque do tema ou android: textColorLink se este atributo estiver definido no tema".

Aqui está o caminho para fazê-lo com segurança.

 private class CustomClickableSpan extends ClickableSpan {

    private int color = -1;

    public CustomClickableSpan(){
        super();
        if(getContext() != null) {
            color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
        }
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        ds.setColor(color != -1 ? color : ds.linkColor);
        ds.setUnderlineText(true);
    }

    @Override
    public void onClick(@NonNull View widget) {
    }
}

Então para usá-lo.

   String text = "my text with action";
    hideText= new SpannableString(text);
    hideText.setSpan(new CustomClickableSpan(){

        @Override
        public void onClick(@NonNull View widget) {
            // your action here !
        }

    }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    yourtextview.setText(hideText);
    // don't forget this ! or this will not work !
    yourtextview.setMovementMethod(LinkMovementMethod.getInstance());

Espero que isso ajude fortemente!


1

Nos documentos do desenvolvedor, para alterar a cor e o tamanho de um spannable:

1- criar uma classe:

    class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {

    override fun updateDrawState(textPaint: TextPaint?) {
        super.updateDrawState(textPaint)
        textPaint?.color = color
    } 
}

2 Crie seu spannable usando essa classe:

    val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
    RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
    titleNames.length - microbe.name.length, // start
    titleNames.length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.