Getting the range of an applied span in SpannableString - android

I am trying to get the set of applied spans on a SpannableString and then find the ranges in which they have been applied. Is that possible? As far as I have seen, there doesn't seem to be a built in method to do this. Am I right?
Object[] spans = spannableString.getSpans(0, spannableString.length(), Object.class);
List<Object> spanArray = asList(spans);
for (Object span: spanArray) {
if (span.getClass().equals(MyCustomSpan.class)) {
MyCustomSpan s = (MyCustomSpan) span;
// Get the range in spannableString where this span has been applied.
// How do I do this?
}
}

Call getSpanStart() and getSpanEnd() to retrieve the start and end positions within the Spanned where the span is applied.

Related

Issue with spannable and Ellipsize in TextView

I have a news feed in my app. In a feed item I have a text view which may have url links and hashtags. I need the both the urls and the hashtags to be clickable which is implemented.
protected void setTextClickable(TextView txtView) {
L.i(getClass().getSimpleName(), "SET TEXT CLICKABLE ENTERED" + "LINES: " +String.valueOf(mTextViewLines));
String text = txtView.getText().toString();
ExpandableTextViewClickableSpan clickSpan = null;
ExpandableTextViewClickableSpan clickableSpan = null;
final SpannableString hashTagInText = new SpannableString(text);
String regexURL = "\\(?\\b((http|https)://|www[.])[-A-Za-z0-9+&##/%?=~_()|!:,.;]*[-A-Za-z0-9+&##/%=~_()|]";
String regexHashTag = "#([A-Za-z0-9_-]+)";
Matcher matcherURL = Pattern.compile(regexURL).matcher(hashTagInText);
Matcher matcherHashTag = Pattern.compile(regexHashTag).matcher(hashTagInText);
int color = view.getResources().getColor(R.color.tinted_green_colour);
while (matcherURL.find()) {
clickSpan = new ExpandableTextViewClickableSpan(currentFragment, false, color, hashTagInText,
matcherURL.start(), matcherURL.end(), MenuUtils.sURL_LINKID);
hashTagInText.setSpan(clickSpan, matcherURL.start(), matcherURL.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
while (matcherHashTag.find()) {
clickableSpan = new ExpandableTextViewClickableSpan(currentFragment, false, color, hashTagInText,
matcherHashTag.start(), matcherHashTag.end(), MenuUtils.sHASHTAG_LINKID);
hashTagInText.setSpan(clickableSpan, matcherHashTag.start(), matcherHashTag.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
However, there is also the requirement that if the message is longer than 4 lines then I ellipsis and show a view more/less option.
Since introducing the method to colour and set clickable the urls and hashtags (which works with spannables which then renders the ellipsis ineffective).
So now my ellipsis doesn't work. I came across this Spannable Ellipsis Issue on SO. However this requires a line count which I can't get unless it's done in a global layout listener.
Which I have done and successfully get the line count. The problem is however that the bind data method is called in which the spannable is applied and layout populated (where I want to apply my own ellipsis method) before the onGlobalLayout method is called, which then leaves me with 0 line count.
Is there a simple way to combine both ellipsis and spannable? Any help is appreciated.

Inconsistent SpannableString setSpan() coloring?

I'm trying to color only vowels in my String 1 color (ex red), and non-vowels another (ex: blue). But the SpannableString setSpan() method is being inconsistent when iterating thru each char. The function is detecting the vows and non-vows correctly, as I had checked the logged output,except that the coloring is not correct:
//ColorLogic.java:
public SpannableString colorString(String myStr)
{
SpannableString spnStr=new SpannableString(myStr);
ForegroundColorSpan vowColor=new ForegroundColorSpan(Color.RED);
ForegroundColorSpan conColor=new ForegroundColorSpan(Color.BLUE);
int strLen=myStr.length();
for(int i=0; i< strLen; i++)
{
if (vowSet.contains(Character.toLowerCase(myStr.charAt(i))))
//if (i%2==0)
{
Log.v(DTAG, "vow"+myStr.charAt(i));
spnStr.setSpan(vowColor, i, i, 0);
}
else
{
Log.v(DTAG, "cons"+myStr.charAt(i));
spnStr.setSpan(conColor, i, i, 0);
}
}
return spnStr;
}
//In my OnCreate of my activity class:
//PASS
//Log.v(DTAG, message);
// 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);
//Log.v(DTAG, "spnMsg: "+spnMsg.toString());
textView.setText(spnMsg, BufferType.SPANNABLE);
//textView.setTextColor(Color.GREEN);
setContentView(textView);
}
![Vows Only its correct (non-vowels only is correct as well)][1]
![With cons and vows, 2 letters then its incorrect!][2]
You cannot reuse span objects. As pskink indicates, please use distinct ForegroundColorSpan objects for each setSpan() call.
Also, you may wish to use fewer spans overall. While your sample ("abibobu") requires the maximum possible number of spans, most words have consonants and vowels strung together. For example, the word "consonant" has two two-consonant spans ("ns" and "nt"). Those could be colored using a single ForegroundColorSpan, rather than two, improving rendering speed. Spans are easy but not the fastest, and so the fewer spans you use, the better your app will perform, particularly in animated situations (e.g., scrolling in a ListView).
Furthermore, you may only need to color either consonants or vowels, unless you are planning on a third color for hyphens and apostrophes. Remember: your text can start with a color (e.g., android:textColor).

Get Spannable String from EditText

I have set a SpannableString to an EditText, now I want to get this text from the EditText and get its markup information. I tried like this:
SpannableStringBuilder spanStr = (SpannableStringBuilder) et.getText();
int boldIndex = spanStr.getSpanStart(new StyleSpan(Typeface.BOLD));
int italicIndex = spanStr.getSpanStart(new StyleSpan(Typeface.ITALIC));
But it gives index -1 for both bold and italic, although it is showing text with italic and bold.
Please help.
From the code you've posted, you're passing new spans to spanStr and asking it to find them. You'll need to have a reference to the instances of those spans that are actually applied. If that's not feasible or you don't want to track spans directly, you can simply call
getSpans to get all the spans applied. You can then filter that array for what you want.
If you don't care about the spans in particular, you can also just call Html.toHtml(spanStr) to get an HTML tagged version.
edit: to add code example
This will grab all applied StyleSpans which is what you want.
/* From the Android docs on StyleSpan: "Describes a style in a span.
* Note that styles are cumulative -- both bold and italic are set in
* separate spans, or if the base is bold and a span calls for italic,
* you get bold italic. You can't turn off a style from the base style."*/
StyleSpan[] mSpans = et.getText().getSpans(0, et.length(), StyleSpan.class);
Here's a link to the StyleSpan docs.
To pick out the spans you want if you have various spans mixed in to a collection/array, you can use instanceof to figure out what type of spans you've got. This snippet will check if a particular span mSpan is an instance of StyleSpan and then print its start/end indices and flags. The flags are constants that describe how the span ends behave such as: Do they include and apply styling to the text at the start/end indices or only to text input at an index inside the start/end range).
if (mSpan instanceof StyleSpan) {
int start = et.getSpanStart(mSpan);
int end = et.getSpanEnd(mSpan);
int flag = et.getSpanFlags(mSpan);
Log.i("SpannableString Spans", "Found StyleSpan at:\n" +
"Start: " + start +
"\n End: " + end +
"\n Flag(s): " + flag);
}

Android - Highlight a Word In a TextView?

I have a database search query which search in the database for a word entered by the user and return a Cursor.
In my ListActivity, I have a ListView which will hold the items (the Cursor items). The ListView items layout is basically a TextView. I mean, the ListView will be a list of TextView's.
What I want is to highlight the search term wherever it appears in the TextView. I mean by highlighting: different color or different background color or anything makes it different than the rest of the text.
Is this possible? and how?
Update:
cursor = myDbHelper.search(term); //term: a word entered by the user.
cursor.moveToFirst();
String[] columns = {cursor.getColumnName(1)};
int[] columnsLayouts = {R.id.item_title}; //item_title: the TextView holding the one raw
ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
lv = getListView();
lv.setAdapter(ca);
For #Shailendra: The search() method will return some titles. I want to highlight the words in those titles that matches the term word. I hope this is clear now.
insert HTML code for color around word and set it to your textView .
like
String newString = oldString.replaceAll(textToHighlight, "<font color='red'>"+textToHighlight+"</font>");
textView.setText(Html.fromHtml(newString));
TextView textView = (TextView)findViewById(R.id.mytextview01);
//use a loop to change text color
Spannable WordtoSpan = new SpannableString("partial colored text");
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan);
The numbers 2 and 4 are start/stop indexes for the coloring of the text, in this example "rti" would be colored.
So you would basically just find the starting index of your searching word in the title:
int startIndex = titleText.indexOf(term);
int stopIndex = startIndex + term.length();
and then replace the numbers 2 and 4 with the indexes and "partial colored text" with your title string.
source: https://stackoverflow.com/a/10279703/2160827
More Easy Way
You can use Spannable class for highlighting/formatting part of Text.
textView.setText("Hello, I am Awesome, Most Awesome"); // set text first
setHighLightedText(textView, "a"); // highlight all `a` in TextView
Here is the method.
/**
* use this method to highlight a text in TextView
*
* #param tv TextView or Edittext or Button (or derived from TextView)
* #param textToHighlight Text to highlight
*/
public void setHighLightedText(TextView tv, String textToHighlight) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToHighlight, 0);
Spannable wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
// set color here
wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
You can check this answer for clickable highlighted text.
I know it's old question but i have created a method to highlight a repeated-word in string\paragraph.
private Spannable highlight(int color, Spannable original, String word) {
String normalized = Normalizer.normalize(original, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
int start = normalized.indexOf(word);
if (start < 0) {
return original;
} else {
Spannable highlighted = new SpannableString(original);
while (start >= 0) {
int spanStart = Math.min(start, original.length());
int spanEnd = Math.min(start+word.length(), original.length());
highlighted.setSpan(new ForegroundColorSpan(color), spanStart,
spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
start = normalizedText.indexOf(word, spanEnd);
}
return highlighted;
}
}
usage:
textView.setText(highlight(primaryColor, textAll, wordToHighlight));
Based on the previous answers I developed the following function, you can copy/paste it
private void highlightMask(TextView textView, String text, String mask) {
boolean highlightenabled = true;
boolean isHighlighted = false;
if (highlightenabled) {
if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(mask)) {
String textLC = text.toLowerCase();
mask = mask.toLowerCase();
if (textLC.contains(mask)) {
int ofe = textLC.indexOf(mask, 0);
Spannable wordToSpan = new SpannableString(text);
for (int ofs = 0; ofs < textLC.length() && ofe != -1; ofs = ofe + 1) {
ofe = textLC.indexOf(mask, ofs);
if (ofe == -1) {
break;
} else {
// set color here
wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + mask.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(wordToSpan, TextView.BufferType.SPANNABLE);
isHighlighted = true;
}
}
}
}
}
if (!isHighlighted) {
textView.setText(text);
}
}
I haven't done it but this looks promising:
http://developer.android.com/reference/android/text/SpannableString.html
http://developer.android.com/guide/topics/resources/string-resource.html
public final void setText (CharSequence text)
Since: API Level 1 Sets the string value of the TextView. TextView
does not accept HTML-like formatting, which you can do with text
strings in XML resource files. To style your strings, attach
android.text.style.* objects to a SpannableString, or see the
Available Resource Types documentation for an example of setting
formatted text in the XML resource file.
http://developer.android.com/reference/android/widget/TextView.html
Try this library Android TextHighlighter.
Implementations
TextView.setText() gets a parameter as Spannable not only CharacterSequence. SpannableString has a method setSpan() which allows applying styles.
See list of direct subclass form CharacterStyle https://developer.android.com/reference/android/text/style/CharacterStyle.html
example of giving background color and foreground color for word "Hello" in "Hello, World"
Spannable spannable = new SpannableString("Hello, World");
// setting red foreground color
ForegroundSpan fgSpan = new ForegroundColorSpan(Color.red);
// setting blue background color
BackgroundSpan bgSpan = new BackgroundColorSPan(Color.blue);
// setSpan requires start and end index
// in our case, it's 0 and 5
// You can directly set fgSpan or bgSpan, however,
// to reuse defined CharacterStyle, use CharacterStyle.wrap()
spannable.setSpan(CharacterStyle.wrap(fgSpan), 0, 5, 0);
spannable.setSpan(CharacterStyle.wrap(bgSpan), 0, 5, 0);
// apply spannableString on textview
textView.setText(spannable);
You do so in xml strings if your strings are static
<string name="my_text">This text is <font color='red'>red here</font></string>
I know this thread is old, but just in case anyone is looking to highlight strings in a textview, I have created a library that does exactly this. This is my first answer to a question on stack overflow, as I have just joined, hopefully it's formatted properly and relevant. It uses SpannableString and will locate all occurrences of a string you specify. Additionally, a custom ClickableSpan is built in giving you the option to set up listeners for text clicked if desired.
Linker
Lightweight android library for highlighting Strings inside of a textview (ignoring case), with optional callbacks.
Language: Java
MinSDK: 17
An image of it's functionality and all of the code can be found
here.
JavaDocs
To bring into your android project implement the artifact:
In the Project level build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
In the App level build.gradle
dependencies {
implementation 'com.github.Gaineyj0349:Linker:1.2'
}
How to use:
1 - Construct a Linker object with a textview:
Linker linker = new Linker(textView);
2 - Add an array or a list of strings to be highlighted within the textview's text:
ArrayList<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
linker.addStrings(list);
AND/OR
String[] words = new String[]{"One", "Two", "Three"};
linker.addStrings(words);
3 - Add a callback: (this is optional):
linker.setListener(new LinkerListener() {
#Override
public void onLinkClick(String charSequenceClicked) {
// charSequenceClicked is the word that was clicked
Toast.makeText(MainActivity.this, charSequenceClicked, Toast.LENGTH_SHORT).show();
}
});
4 - Call the linker's update method to commit customization and rollout the setup.:
linker.update();
You always have the option to add Strings to the linker object, just make sure you call the update method after to refresh the spans.
linker.addStrings("yoda");
linker.update();
If you need a fresh slate with same linker object just call
linker.clearLinksList()
You can customize the links also:
1 - Customize all the link colors:
linker.setAllLinkColors(Color.BLUE);
2 - Customize link underlines:
linker.setAllLinkUnderline(false);
3 - If you wish to customize a color or underline setting for a certain string (note the string must already be added to the linker):
linker.setLinkColorForCharSequence("world", Color.MAGENTA);
linker.setUnderlineModeForCharSequence("world", true);
4 - If you wish to use different setups for every word then you can also give the linker object a list or array of LinkProfiles:
ArrayList<LinkProfile> profiles = new ArrayList<>();
profiles.add(new LinkProfile("hello world",
Color.GREEN, false));
profiles.add(new LinkProfile("goodbye cruel world",
Color.RED, false));
profiles.add(new LinkProfile("Whoa awesome!",
Color.CYAN, true));
linker.addProfiles(profiles);
Just remember to call .update() after any additions to the linker object.
Note that the library will take care of subtleties like adding two of the same words, or same parts of a word. For example if "helloworld" and "hello" are two of the words added to the linker, "helloworld" will be given preference over "hello" when they are in the same span of characters. The linker will sort according to larger words first and trace all spans as it links them - avoiding the issue of duplication as well as intersecting spans.
Licensed under MIT license .

Can I change TextView link text after using Linkify?

Is is possible to change TextView text after using Linkify to create links? I have something where I want the url to have two fields, a name and id, but then I just want the text to display the name.
So I start off with a textview with text that includes both name and id, and linkify to create the appropriate links with both fields. But for the display, I don't want to show the id.
Is this possible?
It's kind of a pain but yes. So Linkify basically does a few things. First it scans the contents of the textview for strings that match that of a url. Next it creates UrlSpan's and ForegroundColorSpan's for those sections that match it. Then it sets the MovementMethod of the TextView.
The important part here are the UrlSpan's. If you take your TextView and call getText(), notice it returns a CharSequence. It's most likely some sort of Spanned. From the Spanned you can ask, getSpans() and specifcally the UrlSpans. Once you know all those spans you can than loop through the list and find and replace the old span objects with your new span objects.
mTextView.setText(someString, TextView.BufferType.SPANNABLE);
if(Linkify.addLinks(mTextView, Linkify.ALL)) {
//You can use a SpannableStringBuilder here if you are going to
// manipulate the displayable text too. However if not this should be fine.
Spannable spannable = (Spannable) mTextView.getText();
// Now we go through all the urls that were setup and recreate them with
// with the custom data on the url.
URLSpan[] spans = spannable.getSpans(0, spannable.length, URLSpan.class);
for (URLSpan span : spans) {
// If you do manipulate the displayable text, like by removing the id
// from it or what not, be sure to keep track of the start and ends
// because they will obviously change.
// In which case you may have to update the ForegroundColorSpan's as well
// depending on the flags used
int start = spannable.getSpanStart(span);
int end = spannable.getSpanEnd(span);
int flags = spannable.getSpanFlags(span);
spannable.removeSpan(span);
// Create your new real url with the parameter you want on it.
URLSpan myUrlSpan = new URLSpan(Uri.parse(span.getUrl).addQueryParam("foo", "bar");
spannable.setSpan(myUrlSpan, start, end, flags);
}
mTextView.setText(spannable);
}
Hopefully that makes sense. Linkify is just a nice tool to setup the correct Spans. Spans just get interpreted when rendering text.
Greg's answer doesn't really answer the original question. But it does contain some insight as to where to start. Here's a function that you can use. It assumes that you have Linkified your textview prior to this call. It's in Kotlin, but you can get the gist of it if you are using Java.
In short, it builds a new Spannable with your new text. During the build, it copies over the url/flags of the URLSpans that the Linkify call created previously.
fun TextView.replaceLinkedText(pattern: String) { // whatever pattern you used to Linkify textview
if(this.text !is Spannable) return // no need to process since there are no URLSpans
val pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)
val matcher = pattern.matcher(this.text)
val linkifiedText = SpannableStringBuilder()
var cursorPos = 0
val spannable = this.text as Spannable
while (matcher.find()) {
linkifiedText.append(this.text.subSequence(cursorPos, matcher.start()))
cursorPos = matcher.end()
val span = spannable.getSpans(matcher.start(), matcher.end(), URLSpan::class.java).first()
val spanFlags = spannable.getSpanFlags(span)
val tag = matcher.group(2) // whatever you want to display
linkifiedText.append(tag)
linkifiedText.setSpan(URLSpan(span.url), linkifiedText.length - tag.length, linkifiedText.length, spanFlags)
}
this.text = linkifiedText
}

Categories

Resources