is Spannable text customizable? Android - android

String aux = getInserzionista(offerta.getIdInserzionista());
sotto_titolo.setText("Offerta dal " + aux);
int inizio = 12;
int fine = 11+aux.length();
sotto_titolo.setMovementMethod(LinkMovementMethod.getInstance());
sotto_titolo.setText(sotto_titolo.getText().toString(),BufferType.SPANNABLE);
Spannable mySpannable = (Spannable) sotto_titolo.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
}
};
//if i put this, not work
mySpannable.setSpan(new ForegroundColorSpan(Color.RED), inizio, fine, 0);
mySpannable.setSpan(myClickableSpan, inizio, fine + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
But if i put this:
mySpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0);
It works, because the text from 0 to 4 is colored!
So, my question is:
How can I change the color of the link (the one colored blue and underlined)?
Thanks

because you set a static value 4 in this line mySpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0);. Set text length in place of 4.

Have you tried using updateDrawState()?

Related

change string color programmatically depending if condition

Is it possible to set multiple colors for different pieces of text inside a TextView with if condition?
Here is my code:
mColoredText = findViewById(R.id.questionText);
String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
SpannableStringBuilder builder = new SpannableStringBuilder();
if(mColoredString.contains("RED")) {
String red = "RED";
SpannableString redSpannable = new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);
}
if(mColoredString.contains("YELLOW")) {
String yellow = "YELLOW";
SpannableString whiteSpannable = new SpannableString(yellow);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, yellow.length(), 0);
builder.append(whiteSpannable);
}
if(mColoredString.contains("BLUE")) {
String blue = "BLUE";
SpannableString blueSpannable = new SpannableString(blue);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(blueSpannable);
}
mColoredText.setText(builder, TextView.BufferType.SPANNABLE);
But the end result is always print: RED YELLOW BLUE with it's color, just three text.
I expect BLACK RED GREEN YELLOW ORANGE BLUE WHITE written all together, and white color applicable if no spannable color.
Try this code..
textView = findViewById(R.id.tvData);
String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
SpannableStringBuilder builder = new SpannableStringBuilder();
String strArray[] = mColoredString.split(" ");
for (int i = 0; i < strArray.length; i++) {
if (strArray[i].equals("RED")) {
SpannableString redSpannable = new SpannableString(strArray[i]);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, strArray[i].length(), 0);
builder.append(redSpannable);
} else if (strArray[i].equals("YELLOW")) {
SpannableString whiteSpannable = new SpannableString(strArray[i]);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, strArray[i].length(), 0);
builder.append(whiteSpannable);
} else if (strArray[i].equals("BLUE")) {
SpannableString blueSpannable = new SpannableString(strArray[i]);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, strArray[i].length(), 0);
builder.append(blueSpannable);
} else {
builder.append(strArray[i]);
}
}
textView.setText(builder);
}
You create a new builder and add only RED YELLOW and BLUE colors to it. That is why you see always RED YELLOW BLUE.
If you want to update the original text then you have to make a SpannableString from it first.
SpannableString mColoredString = new SpannableString("BLACK RED GREEN YELLOW ORANGE BLUE WHITE");
if (mColoredString.toString().contains("RED")) {
mColoredString.setSpan(new ForegroundColorSpan(Color.RED), 6, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (mColoredString.toString().contains("YELLOW")) {
mColoredString.setSpan(new ForegroundColorSpan(Color.YELLOW), 16, 22, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (mColoredString.toString().contains("BLUE")) {
mColoredString.setSpan(new ForegroundColorSpan(Color.BLUE), 30, 34, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
questionText.setText(mColoredString);
Please read this article for a detailed explanation.
EDIT:
If you don't know the start and end positions then you have to calculate them:
if (mColoredString.toString().contains("YELLOW")) {
int start = mColoredString.toString().indexOf("YELLOW");
int end = start + "YELLOW".length();
mColoredString.setSpan(new ForegroundColorSpan(Color.YELLOW), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

TextView with string and clickable text

I am trying to use a TextView to display some text, part of the text needs to be clickable to open another activity.
Here is what I have so far:
var byArtistNameView = view.FindViewById<TextView> (Resource.Id.ArtistName2);
var ss = new SpannableString("By " + item.Artist.ArtistName);
var clickableSpan = new MyClickableSpan();
clickableSpan.Click = x => view.Context.StartActivity(new Intent(view.Context, typeof(MainActivity)));
ss.SetSpan(new ForegroundColorSpan(Color.Gray), 0, 2, SpanTypes.ExclusiveExclusive);
ss.SetSpan(clickableSpan, 3, ss.Length(), SpanTypes.ExclusiveExclusive);
ss.SetSpan (new NoUnderlineSpan (), 3, ss.Length(), SpanTypes.ExclusiveExclusive);
ss.SetSpan(new ForegroundColorSpan(view.Resources.GetColor (Resource.Color.link_text)), 3, ss.Length(), SpanTypes.ExclusiveExclusive);
byArtistNameView.TextFormatted = ss;
byArtistNameView.MovementMethod = LinkMovementMethod.Instance;
private class MyClickableSpan : ClickableSpan
{
public Action<View> Click;
public override void OnClick(View widget)
{
if (Click != null)
Click(widget);
}
}
The text is blank / not visible if i set the MovementMethod to LinkMovementMethod.Instance, if i comment out this line then the text is visible and in the correct format, but just not clickable.
Any idea where I am going wrong here?
Thank You.

Alternate coloring of each character of a string with setSpan() not coloring correctly Android?

I'm trying to do an alternate coloring of each character of an input string using SpannableString's setSpan(), but somehow the outputted string is not colored properly.
//ColorLogic.java:
public SpannableString colorString(String myStr)
{
SpannableString spnStr=new SpannableString(myStr);
int strLen=myStr.length();
for(int i=0; i< strLen; i++)
{
if (i%2==0)
{
Log.v(DTAG, "vow"+myStr.charAt(i));
spnStr.setSpan(new ForegroundColorSpan(Color.RED), i, i, 0);
}
else
{
Log.v(DTAG, "cons"+myStr.charAt(i));
spnStr.setSpan(new ForegroundColorSpan(Color.BLUE), i, i, 0);
}
}
return spnStr;
}
//In my OnCreate of my activity class:
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(50);
//Call Color Logic to color each letter individually
ColorLogic myColorTxt=new ColorLogic();
SpannableString spnMsg=myColorTxt.colorString(message);
textView.setText(spnMsg, BufferType.SPANNABLE);
setContentView(textView);
}
output:
![2 letters][1]
[1]: http://i.stack.imgur.com/rA8TV.png
![3 letters][1]
[1]: http://i.stack.imgur.com/X039z.png
I have noticed that if I simply have :
spnStr.setSpan(new ForegroundColorSpan(Color.RED), 0, 0, 0);
Then ALL the characters of the string is colored red, even though I had specified the start and stop to be the 1st char. I've tried different Spannable flags such as: android.text.Spannable.SPAN_INCLUSIVE_INCLUSIVE
, but the same problem still occurs.
You're specifing i for both start and end - this means you're specifying a span of length 0, not a span of length 1. Try this:
spnStr.setSpan(new ForegroundColorSpan(Color.RED), i, i + 1, 0);

How to clear formatting from an EditText?

I have an EditText, and can add formatting such as bold, italic....but how can I remove it? I've looked into getSpans, filters, and other non-string things and haven't been able to make sense of them! Ideally, I'd like to be able to clear specific tags and all tags set around the selected text.
Update with my solution:
private String getSelectedText(){
int start = Math.max(mText.getSelectionStart(), 0);
int end = Math.max(mText.getSelectionEnd(), 0);
return mText.getText().toString().substring(Math.min(start, end), Math.max(start, end));
}
private void clearFormat(){
int s1 = Math.max(mText.getSelectionStart(), 0);
int s2 = Math.max(mText.getSelectionEnd(), 0);
String text = getSelectedText(); if(text==""){ return; }
EditText prose = mText;
Spannable raw = new SpannableString(prose.getText());
CharacterStyle[] spans = raw.getSpans(s1, s2, CharacterStyle.class);
for (CharacterStyle span : spans) {
raw.removeSpan(span);
}
prose.setText(raw);
//Re-select
mText.setSelection(Math.min(s1,s2), Math.max(s1, s2));
}
but how can I remove it?
Call removeSpan() on the Spannable.
For example, this method from this sample project searches for a search string in the contents of a TextView and assigns it a background color, but only after removing any previous background colors:
private void searchFor(String text) {
TextView prose=(TextView)findViewById(R.id.prose);
Spannable raw=new SpannableString(prose.getText());
BackgroundColorSpan[] spans=raw.getSpans(0,
raw.length(),
BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index=TextUtils.indexOf(raw, text);
while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}
prose.setText(raw);
}
}
what you could try is:
1- Create a custom style where your EditText will have "such as bold, italic..."
2- Be aware of using R.style.normalText to change it back to it's normal style at runtime
3- Change this styles depending on the behaviour you want to achieve via setTextAppearance(Context context, int resid)
Here is an example i found googling How to change a TextView's style at runtime
Edit: as your question is "How to clear formatting from an EditText" here is the specific answer as code:
editTextToClearStyle.setTextAppearance(this,R.style.normalText);
Please see the comment of the snippet below.
if (makeItalic) {
SpannableString spanString = new SpannableString(textViewDescription.getText());
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
this.textViewDescription.setText(spanString);
} else {
SpannableString spanString = new SpannableString(
textViewDescription.getText().toString()); // NOTE: call 'toString()' here!
spanString.setSpan(new StyleSpan(Typeface.NORMAL), 0, spanString.length(), 0);
this.textViewDescription.setText(spanString);
}
... just get the raw string characters by calling the toString() method.

Custom TextView in android with different color words

Is it possible to have a textview to have different color for every word? Or even every letter? I tried extending textview and creating it but however I thought of the problem is, how would I draw all the the text out at the same time with different colors?
Use android.text.Spannable
final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
new ForegroundColorSpan(Color.BLUE),
wordStart,
wordEnd,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);
EDIT: To make all "Java" green
final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);
final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
spannable.setSpan(
span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
myTextView.setText(spannable);
The SpannableString class allows you to easily format certain pieces (spans) of a string one way and other pieces another by applying extensions of CharacterStyle (i.e. ForegroundColorSpan) via the setSpan method.
You can try This:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
richTextView = (TextView)findViewById(R.id.rich_text);
// this is the text we'll be operating on
SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");
// make "Lorem" (characters 0 to 5) red
text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);
// make "ipsum" (characters 6 to 11) one and a half time bigger than the textbox
text.setSpan(new RelativeSizeSpan(1.5f), 6, 11, 0);
// make "dolor" (characters 12 to 17) display a toast message when touched
final Context context = this;
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
}
};
text.setSpan(clickableSpan, 12, 17, 0);
// make "sit" (characters 18 to 21) struck through
text.setSpan(new StrikethroughSpan(), 18, 21, 0);
// make "amet" (characters 22 to 26) twice as big, green and a link to this site.
// it's important to set the color after the URLSpan or the standard
// link color will override it.
text.setSpan(new RelativeSizeSpan(2f), 22, 26, 0);
text.setSpan(new URLSpan("http://www.chrisumbel.com"), 22, 26, 0);
text.setSpan(new ForegroundColorSpan(Color.GREEN), 22, 26, 0);
// make our ClickableSpans and URLSpans work
richTextView.setMovementMethod(LinkMovementMethod.getInstance());
// shove our styled text into the TextView
richTextView.setText(text, BufferType.SPANNABLE);
}
The result will look like this:
For more detail see Chris Umbel blog.
Yes, you can do this with Spannable and SpannableStringBuilder. See Is there any example about Spanned and Spannable text for one example.
For the various ways to format text (background color, foreground color, clickable, etc.), see CharacterStyle.

Categories

Resources