How to remove span style from SpannableString - android

I was trying to remove style from my SpannableString but unfortunately is not working, my aim is to remove the style when I click on the text.
SpannableString content = new SpannableString("Test Text");
content.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, content.length(), 0);
...
onClick Action :
content.removeSpan(new StyleSpan(Typeface.BOLD_ITALIC)) // not working

Two styleSpan you new is not the same object. You can use a non-anonymous object to point it. Change your code like that:
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD_ITALIC);
content.setSpan(styleSpan , 0, content.length(), 0);
onClick Action:
content.removeSpan(styleSpan);
textView.setText(content);// to redraw the TextView

As Zheng Xingjie pointed out you can remove a particular span with removeSpan() but you need to store the span object.
However, I came across a case that I need to remove a group of the same style spans anonymously, and leave other styles, So I did it by iterating on this particular type of spans as follows:
In my case, it was BackgroundColorSpan, but I will use StyleSpan like it had been asked:
Java
SpannableString content = new SpannableString("Test Text");
content.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, content.length(), 0);
StyleSpan[] spans = content.getSpans(0, content.length(), StyleSpan.class);
for (StyleSpan styleSpan: spans) content.removeSpan(styleSpan);
textview.setText(content);
Kotlin
val content = SpannableString("Test Text")
content.setSpan(StyleSpan(Typeface.BOLD_ITALIC), 0, content.length, 0)
val spans = content.getSpans(0, content.length, StyleSpan::class.java)
for (styleSpan in spans) content.removeSpan(styleSpan)
textview.setText(content)

Related

Spannable style isn't applying

So, i'm having a message which contains text and SpannableStringBuilder which is initialized like this :
final SpannableStringBuilder builder = new SpannableStringBuilder(message.getMessage());
And by default, i'm setting font to BOLD :
builder.setSpan(new StyleSpan(Typeface.BOLD), 0, messageText.length(), 0);
But my message text will be changed, example :
Your question : {question}
Your answer : {answer}
{question} and {answer} are objects that will be replaced with text, replacing is happening like this:
final TextObject question = objects.getQuestion();
spannable = new SpannableString(question.getText());
spannable.setSpan(new StyleSpan(Typeface.NORMAL), 0, spannable.length(), 0);
builder.replace(start, end, spannable);
Text is replacing just fine, but NORMAL font type isn't applying to it, so i have all text BOLD, but i need this parts to be normal
Any help is highly appreciated
You have to add that Spanned.SPAN_INCLUSIVE_INCLUSIVE as a last parameter
spannable.setSpan(new StyleSpan(Typeface.NORMAL), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
and if you want some part in bold and some not you have to be specific which part. The second and the third parameter of setSpan method is responsible for that

Multiple spans in same String

I've got problems to set StyleSpan and ForegroundColorSpan in the same string. Here's my code:
SpannableStringBuilder text_1_2 = new SpannableStringBuilder(getString(R.string.why_text_1_2));
StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
ForegroundColorSpan fcs = new ForegroundColorSpan(getResources().getColor(R.color.custom_blue));
text_1_2.setSpan(fcs, 0 , text_1_2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
text_1_2.setSpan(bss, 0, text_1_2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
The resulting string has blue color but is not bold.
Thanks.
Can you try this
text_1_2.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0 , text_1_2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
text_1_2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.custom_blue)), 0, text_1_2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
But my recommendation is if you don't want to style a part of the string apply the style and color using
android:textColor="#color/color_name"
android:textStyle="bold"

How to make multi spannable text?

This is example.
String source = "This is example text";
Spannable out = new SpannedString(source);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
out.setSpan(boldSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(boldSpan, 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//someTextView.setText(out);
Expected result: This is example text ("hi" & "xam" are bold)
Actual result:      This is example text (works only last setSpan method and bold is only "xam")
How to make multi spannable text? It's possible?
Maybe problem is in Spannable.SPAN_EXCLUSIVE_EXCLUSIVE flag? Thanks.
I think you need a new StyleSpan for each.
String source = "This is example text";
Spannable out = new SpannedString(source);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
StyleSpan boldSpan2 = new StyleSpan(Typeface.BOLD);
out.setSpan(boldSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(boldSpan2, 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Haven't tried it out though.
The reason is that each bold spannable text must be represented by a StyleSpan. The reason for yours is just the same as reassignment of a value.

combining multi strings and text in android

I'm pretty new to android, Java and sqlite. For my first program I'm creating a program that will take user input and place in predefined text.
Example: "text" string1 "more text" string2 "even more text" etc
My text will be one color and strings will display in another color.
I'm using sqlite to seperate my data and code and this is where I hit a wall. Trying to find help on how I will be able to combine my above text into one row/column in my database table.
Using only one above example i could get this up and running. But there will be 50+ of above example for release making a database a must especially when I want to add more after release.
Most probably you've read up on SpannableStringBuilder, which allows you to add color to the text in your TextView's content. Check out the code below:
SpannableStringBuilder ssb = new SpannableStringBuilder(<your text>);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, ssb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
The code above will work in most cases, however what you want is to have different alternating colors on a single TextView. Then you should do the following:
String text = your_text + text_from_database;
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255 0));
ssb.setSpan(fcs, 0, your_text, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.setSpan(fcs2, your_text.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(ssb);
The above code will now work, but you'll notice that if you add another text your_another_text and want to use the previous fcs instance for a second time, the previously colored your_text will now lose its formatting (color). This time you'll need to create another ForegroundColorSpan fcs3 to format the third part of the SpannableStringBuilder. The key here is to use a character style in a setSpan method only once. See below:
String testTest = "abcdefgh";
String testTest2 = "ijklmnop";
String testTest3 = "qrstuvwxyz";
SpannableStringBuilder ssb = new SpannableStringBuilder(testTest+testTest2+testTest3);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255, 0));
ForegroundColorSpan fcs3 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, testTest.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs2, testTest.length(), (testTest+testTest2).length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
ssb.setSpan(fcs3, (testTest+testTest2).length(), ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
test.setText(ssb);
This method is good if you know you have a fixed number of String elements in your SpannableStringBuilder. If you have wish to have a TextView of dynamic length and number of elements, you need to do this in a different approach. What worked for me was to convert each string element into a SpannableString, use setSpan, and append it to the TextView. This is useful if you're using a loop to build your TextView.
TextView test = (TextView)findViewById(R.id.test);
String testTest = "abcdefgh";
String testTest2 = "ijklmnop";
String testTest3 = "qrstuvwxyz";
SpannableString ssb = new SpannableString(testTest);
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ForegroundColorSpan fcs2 = new ForegroundColorSpan(Color.rgb(0, 255, 0));
ForegroundColorSpan fcs3 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
ssb.setSpan(fcs, 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.setText(ssb);
SpannableString ssb2 = new SpannableString(testTest2);
ssb2.setSpan(fcs2, 0, ssb2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.append(ssb2);
SpannableString ssb3 = new SpannableString(testTest3);
ssb3.setSpan(fcs3, 0, ssb3.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
test.append(ssb3);

Set color of TextView span in Android

Is it possible to set the color of just span of text in a TextView?
I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:
(source: twimg.com)
Another answer would be very similar, but wouldn't need to set the text of the TextView twice
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);
Here is a little help function. Great for when you have multiple languages!
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);
}
I always find visual examples helpful when trying to understand a new concept.
Background Color
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);
Foreground Color
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);
Combination
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);
Further Study
Explain the meaning of Span flags like SPAN_EXCLUSIVE_EXCLUSIVE
Android Spanned, SpannedString, Spannable, SpannableString and CharSequence
If you want more control, you might want to check the TextPaint class. Here is how to use it:
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);
}
};
Set your TextView´s text spannable and define a ForegroundColorSpan for your text.
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);
Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.
If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:
<TextView
android:id="#+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorLink="#color/your_color"
</TextView>
You can also set it in the code with:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);
Here's a Kotlin Extension Function I have for this
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 it after you have set your text to the TextView like so
private val blueberry by lazy { getColor(R.color.blueberry) }
textViewTip.setColouredSpan("Warning", blueberry)
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;
}
Output:
Set Color on Text by passing String and color:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Set text on TextView / Button / EditText etc by calling below code:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
Get Colored String:
String name = getColoredSpanned("Hiren", "#800000");
Set Text on TextView:
txtView.setText(Html.fromHtml(name));
Done
There's a factory for creating the Spannable, and avoid the cast, like this:
Spannable span = Spannable.Factory.getInstance().newSpannable("text");
Just to add to the accepted answer, as all the answers seem to talk about android.graphics.Color only: what if the color I want is defined in res/values/colors.xml?
For example, consider Material Design colors defined in colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="md_blue_500">#2196F3</color>
</resources>
(android_material_design_colours.xml is your best friend)
Then use ContextCompat.getColor(getContext(), R.color.md_blue_500) where you would use Color.BLUE, so that:
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
becomes:
wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Where I found that:
Working with spans in Android – Michael Spitsin – Medium
Using kotlin-ktx, you can achieve it easily
bindView?.oneTimePasswordTitle?.text = buildSpannedString {
append("One Time Password ")
inSpans(
ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
){
append(" (As Registered Email)")
}
}
Some answers here aren't up to date. Because, you will (in most of cases) add a custom clic action on your link.
Besides, as provided by the documentation help, your spanned string link color will have a default one.
"The default link color is the theme's accent color or android:textColorLink if this attribute is defined in the theme".
Here is the way to do it safely.
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) {
}
}
Then to use it.
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());
Hope this will strongly help !
create textview in ur layout
paste this code in ur 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
Below works perfectly for me
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);
Output for above code
From the developer docs, to change the color and size of a spannable:
1- create a class:
class RelativeSizeColorSpan(size: Float,#ColorInt private val color: Int): RelativeSizeSpan(size) {
override fun updateDrawState(textPaint: TextPaint?) {
super.updateDrawState(textPaint)
textPaint?.color = color
}
}
2 Create your spannable using that class:
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
)
You can use extension function in Kotlin
fun CharSequence.colorizeText(
textPartToColorize: CharSequence,
#ColorInt color: Int
): CharSequence = SpannableString(this).apply {
val startIndexOfText = this.indexOf(textPartToColorize.toString())
setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}
Usage:
val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))
viewBinding.myTextView.text = myTextToColorize
Now you can use the CodeView library to highlight patterns with different colors easily, for example, to highlight all URLs inside the text with the blue color you just need to write
CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);
CodeView Repository URL: https://github.com/amrdeveloper/codeview
I got the same issue.
#Dano's answer is absolutely correct. But it doesn't work for me.
After that, I found the issue I have added ClickableSpan. So it will change my color with another color (accent color)
Issue
SpannableStringBuilder will not change color and undline when you add a ClickableSpan after ForegroundColorSpan or UnderlineSpan.
Solution
1. With ClickableSpan
You can Override the updateDrawState method inside ClickableSpan.
In the updateDrawState method, you should remove the super callback.
After that, you should Modify your text paint as required.
2. Without ClickableSpan
Add ForegroundColorSpan to change the text color
Add UnderlineSpan to add underline in text.
First Part **Second Part should be Bold** last Part
This text should be changed using SpannableString
import android.graphics.Typeface.BOLD
import android.text.Spannable
import android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
val firstPart = "First Part "
val secondPart = "Second Part should be Bold"
val thirdPart = " last Part"
val finalString = firstPart + secondPart + thirdPart
val sb: Spannable = SpannableString(finalString).also {
// ... Change text Colour
it.setSpan(
ForegroundColorSpan(getColor(requireContext(), R.color.pink)),
finalString.indexOf(secondPart),
finalString.indexOf(secondPart) + secondPart.length,
SPAN_EXCLUSIVE_EXCLUSIVE
)
// ... Make the text Bold
it.setSpan(
StyleSpan(BOLD),
finalString.indexOf(secondPart),
finalString.indexOf(secondPart) + secondPart.length,
SPAN_EXCLUSIVE_EXCLUSIVE
)
// ... Change Background Colour
it.setSpan(
BackgroundColorSpan(getColor(requireContext(), R.color.lightPink)),
finalString.indexOf(secondPart) - 1,
finalString.indexOf(secondPart) + secondPart.length + 1,
SPAN_EXCLUSIVE_EXCLUSIVE
)
}
yourTextView.text = sb

Categories

Resources