Get Spannable String from EditText - android

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);
}

Related

Bold Text in TextView does not work with combination of Spanned and String

I have this code
TextView text1 = (TextView) view.findViewById(R.layout.myLayout);
Spanned myBold = (Html.fromHtml("<b>Test<b>", Html.FROM_HTML_MODE_LEGACY));
If I do
text1.setText(myBold);
Then myBold is in bold,which is ok. But when I want to add a string more, like
text1.setText(myBold+"bla");
Then the whole TextView is not bold anymore. Why does the new String "bla" affect this?
Thanks.
Why does the new String "bla" affect this?
Because what you are really doing is:
text1.setText(myBold.toString() + "bla");
A String has no style information. A Spanned object does.
Use TextUtils.concat() instead:
text1.setText(TextUtils.concat(myBold, "bla"));
A better choice would be to use a Bold StyleSpan. In the next sample only the "hello" world will be set to bold by using such technique:
Java:
final SpannableString caption = new SpannableString("hello world");
// Set to bold from index 0 to the length of 'hello'
caption.setSpan(new StyleSpan(Typeface.BOLD), 0, "hello".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
yourTextView.setText(caption);
Kotlin:
yourTextView.text = SpannableString("hello world").apply {
// Set to bold from index 0 to the length of 'hello'
setSpan(StyleSpan(Typeface.BOLD), 0, "hello".length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE))
}
This would be a more optimal solution rather than using the Html.fromHtml technicque, as it doesn't have to go through the overhead of parsing/interpreting the HTML tags.
In addition, it allows you to combine more styles, sizes, etc, in the same SpannableString.

getTypeFace from a character

Formatted text appears in a edittext.But the string contains multiple styling .
Is it possible to get the styling used on a particular character in a string , using getTypeFace command.
The first question is how to you set that styling?
If your doing something like Html.fromHtml("hello") calling getTypeFace() will return 0 (TypeFace.NORMAL). For this I would say that you might need to make the parse yourself and create substrings according to the HTML tags you've found.
If you your using the TextView attributes for this - android:textStyle="bold"
You can call directly:
Log.d(TAG, "has typeface=${tv_typeface.typeface.style}")
Alternatively if you're using SpannableStrings to edit how your text should look
You can do something like:
//Set an italic style to the word "hello"
val spannableString = SpannableString("hello world")
spannableString.setSpan(StyleSpan(Typeface.ITALIC), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tv_typeface.text = spannableString
//Get the style italic used
val spannedString = tv_typeface.text as SpannedString
val spans = spannedString.getSpans(0, tv_typeface.length(), StyleSpan::class.java)
for (span in spans) {
Log.d(TAG, "StyleSpan between: ${spannedString.getSpanStart(span)} and ${spannedString.getSpanEnd(span)} with style ${span.style}")
}

display value of "a" in bold and different color

if (Global.DigsSinceLogin > 3) {
int a = Global.DigsSinceLogin;
noCoachingPoints.setText("Excellent Job! \n No Coaching Points Triggered in the Last "+ a +" Digs");}
Requirement:
Need to display value of "a" as 1)bold and 2)yellow color.
Is there a way i can display this value with the above changes and display in the same position
Try Below Code
if (Global.DigsSinceLogin > 3) {
int a = Global.DigsSinceLogin;
noCoachingPoints.setText(Html.fromHtml("Excellent Job!"+"<br>"+" No Coaching Points Triggered in the Last "+ "<font color=yellow><B>" + a + "</B></font>"+" Digs"));}
You can use a SpannableString or SpannableStringBuilder and apply both a StyleSpan and a ForegroundColorSpan to the text that needs special treatment. This much is pretty straightforward; I think the more difficult part will be finding the proper index of the character(s) in the string, especially when you start using localized string resources (which you should).

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).

How to make part of the text Bold in android at runtime?

A ListView in my application has many string elements like name, experience, date of joining, etc. I just want to make name bold. All the string elements will be in a single TextView.
my XML:
<ImageView
android:id="#+id/logo"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/logo"
android:padding="5dp"
android:textSize="12dp" >
</TextView>
My code to set the TextView of the ListView item:
holder.text.setText(name + "\n" + expirience + " " + dateOfJoininf);
Let's say you have a TextView called etx. You would then use the following code:
final SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); //Span to make text italic
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(iss, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
etx.setText(sb);
Based on Imran Rana's answer, here is a generic, reusable method if you need to apply StyleSpans to several TextViews, with support for multiple languages (where indices are variable):
void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
int start = text.indexOf(spanText);
int end = start + spanText.length();
sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
}
Use it in an Activity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
StyleSpan boldStyle = new StyleSpan(Typeface.BOLD);
setTextWithSpan((TextView) findViewById(R.id.welcome_text),
getString(R.string.welcome_text),
getString(R.string.welcome_text_bold),
boldStyle);
// ...
}
strings.xml
<string name="welcome_text">Welcome to CompanyName</string>
<string name="welcome_text_bold">CompanyName</string>
Result:
Welcome to CompanyName
You can do it using Kotlin and buildSpannedString extension function from core-ktx
holder.textView.text = buildSpannedString {
bold { append("$name\n") }
append("$experience $dateOfJoining")
}
The answers provided here are correct, but can't be called in a loop because the StyleSpan object is a single contiguous span (not a style that can be applied to multiple spans). Calling setSpan multiple times with the same bold StyleSpan would create one bold span and just move it around in the parent span.
In my case (displaying search results), I needed to make all instances of all the search keywords appear bold. This is what I did:
private static SpannableStringBuilder emboldenKeywords(final String text,
final String[] searchKeywords) {
// searching in the lower case text to make sure we catch all cases
final String loweredMasterText = text.toLowerCase(Locale.ENGLISH);
final SpannableStringBuilder span = new SpannableStringBuilder(text);
// for each keyword
for (final String keyword : searchKeywords) {
// lower the keyword to catch both lower and upper case chars
final String loweredKeyword = keyword.toLowerCase(Locale.ENGLISH);
// start at the beginning of the master text
int offset = 0;
int start;
final int len = keyword.length(); // let's calculate this outside the 'while'
while ((start = loweredMasterText.indexOf(loweredKeyword, offset)) >= 0) {
// make it bold
span.setSpan(new StyleSpan(Typeface.BOLD), start, start+len, SPAN_INCLUSIVE_INCLUSIVE);
// move your offset pointer
offset = start + len;
}
}
// put it in your TextView and smoke it!
return span;
}
Keep in mind that the code above isn't smart enough to skip double-bolding if one keyword is a substring of the other. For example, if you search for "Fish fi" inside "Fishes in the fisty Sea" it will make the "fish" bold once and then the "fi" portion. The good thing is that while inefficient and a bit undesirable, it won't have a visual drawback as your displayed result will still look like
Fishes in the fisty Sea
if you don't know exactly the length of the text before the text portion that you want to make Bold, or even you don't know the length of the text to be Bold, you can easily use HTML tags like the following:
yourTextView.setText(Html.fromHtml("text before " + "<font><b>" + "text to be Bold" + "</b></font>" + " text after"));
<string name="My_Name">Given name is <b>Not Right</b>Please try again </string>
use "b" tag in string.xml file.
also for Italic "i" and Underline "u".
Extending frieder's answer to support case and diacritics insensitivity.
public static String stripDiacritics(String s) {
s = Normalizer.normalize(s, Normalizer.Form.NFD);
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
return s;
}
public static void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style, boolean caseDiacriticsInsensitive) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
int start;
if (caseDiacriticsInsensitive) {
start = stripDiacritics(text).toLowerCase(Locale.US).indexOf(stripDiacritics(spanText).toLowerCase(Locale.US));
} else {
start = text.indexOf(spanText);
}
int end = start + spanText.length();
if (start > -1)
sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
}
If you are using the # srings / your_string annotation, access the strings.xml file and use the <b></b> tag in the part of the text you want.
Example:
<string><b>Bold Text</b><i>italic</i>Normal Text</string>
I recommend to use strings.xml file with CDATA
<string name="mystring"><![CDATA[ <b>Hello</b> <i>World</i> ]]></string>
Then in the java file :
TextView myTextView = (TextView) this.findViewById(R.id.myTextView);
myTextView.setText(Html.fromHtml( getResources().getString(R.string.mystring) ));
To better support translations and remove any dependency on length of the string or particular index, you should use android.text.Annotation in you string defined strings.xml.
In your particular case, you can create a string like below
<string name="bold_name_experience_text"><annotation type="bold">name</annotation> \nexpirience dateOfJoininf</string>
or if you want to substitute these in runtime, you can create a string as follow
<string name="bold_name_experience_text"><annotation type="bold">name</annotation> \n%d %s</string>
You must apply this bold_name_experience_text in your text view label. These annotation class spans get added to your string and then you can iterate on them to apply the bold span.
You can refer to my SO answer which shows the Kotlin code to iterate through these spans and apply the bold span
Remember all the above answers has one of the following flows:
They are using some hard-coded index logic which may crash or give wrong results in some other language
They are using hardcode string in Java code which will result in lots of complicated logic to maintain internalisation
Some used Html.fromHtml which can be acceptable answer depending on the use-case. As Html.fromHtml doesn't always work for all types of HTML attributes for example there is not support of click span. Also depending on OEM you might get different rendered TextView

Categories

Resources