How to change some words of a string to BOLD? - android

This is the string which i am getting from web using json api in my code:
String content = "<strong><em>India is the world’s hub for child sex trafficking</em>
</strong></p>\n<p style=\"text-align: center;\"><strong><em>Nearly 40,000 children are
abducted every year… </em></strong></p>\n<p style=\"text-align: center;\"><strong<em>
Every8 minutes a girl child goes missing in India!</em></strong></p>\n<p><strong>Priti
Pathak</strong></p>\n<p>MEET Shivani Shivaji Roy, Senior Inspector, Crime Branch, Mumbai
Police, as she sets out to confront the mastermind behind the child trafficking mafia,"
In this string whatever the text is in
"<strong><em> TEXT </em></strong>"
I want to display it BOLD. So for the above string
<strong><em>India is the world’s hub for child sex trafficking</em></strong>
will be displayed as
India is the world’s hub for child sex trafficking
. This should happen for entire string. This is the code which i am using:
int startIndex = content.indexOf("<strong><em>")+13; // 13 because <strong><em> has 13 characters
String substring = content.substring(startIndex, startIndex+200);
int subendIndex = substring.indexOf("</em></strong>");
int endIndex = startIndex + subendIndex;
SpannableString s = new SpannableString(content);
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);
textview.setText(s, BufferType.SPANNABLE );
This code is working but it is setting bold text only to the text whichever is first within strong tag and not to the rest. Because I am setting bold text only to the first tag.
How should i get the startIndex, endIndex of all the "strong tags" and so i can set
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);
to all the texts and also the number of times i would have to set the span.
I though of using regex also but i dont know how to get indexes using it. Any help would be nice. Thankyou !

The easier way is to use the Html class:
s = Html.fromHtml(content);
See the documentation for the details.

This is the simple way
TextView TV = (TextView)findViewById(R.id.Tv);
String Title="I N <big>D</big> I A";
TV.setText(Html.fromHtml(Title));

If you want to only bold some strings then I recommend Html.fromHtml. A short sample:
String str = "<b> bold text</b> unbold one";
textView.setText(Html.fromHtml(str));
Here's a list of html tags supported by textview.

Use regular HTML tags in Strings, This text uses bold and italics by using inline tags such as within the string file.. Refer this link Hope this Link would be helpful for you!

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.

Android two Textviews, align them as one paragraph

Lets say I have two textviews, a title, and details, the details is toEndOf the title (same line), and while the title is one line, the details, can be multiple, my question is, how can I configure the details textview that when it starts a new line, instead of aligning it to the previous row of the textview, align it to the title textview, hence creating a paragraph feel.
Please see these screenshot to understand what I'm trying to accomplish (the title is the bold text, details it the rest):
Desired:
What I have so far:
The only solution I can think of is using one textview for both, and format the text with HTML, but what if I need a bigger text size for the title?
Thanks!
You can use SpannableText
This will do the job!
<TextView
..
android:id="#+id/text_view"
/>
...
TextView text=(TextView)findViewById(R.id.text_view);
String head = "Seat (s):";
String body = " The baby name means the meaning of the nam";
setTextWithSpan(text,head+body,head, body,new android.text.style.StyleSpan(android.graphics.Typeface.BOLD));
Custom method
public void setTextWithSpan(TextView textView, String text, String spanTextBold,String secondPartOfText,StyleSpan style) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
int start = text.indexOf(spanTextBold);
int end = start + spanTextBold.length();
sb.setSpan(style, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
//sb.setSpan(new ForegroundColorSpan(Color.BLUE), start, end ,0); // if you need a color
int startTwo = text.indexOf(secondPartOfText);
int endTwo = startTwo + secondPartOfText.length();
// sb.setSpan(new StyleSpan(Typeface.ITALIC),startTwo,endTwo , 0);
sb.setSpan(new RelativeSizeSpan(0.8f), startTwo, endTwo, 0);
textView.setText(sb);
}
Yes, As you mentioned, I also see One TextView with different strings sizes/colors for texts inside.
To achieve this you need to use SpannableString - Docs link
Also Check this answer for details
Use SpannableText for your issue to separate two textviews.

Formatting multiple string into one string

So my requirement is as follows:
I've multiple strings stored in different string variables, lot of them are hardcore string, some of them are user inputs, while some are values from database(online as well as offline database.)
I want to combine all the strings in single String variable but I want each letter formatted differently as shown in following image.
where as my normal string would be like this:
MAIN TITLE SUBTITLE: Detail 1 Detail 2 Heading 1: User Input Data Heading 2: User Input Data.
Thank you!
Spannable String is your solution.
Refer this https://developer.android.com/reference/android/text/SpannableString.html
Also refer this
http://androidcocktail.blogspot.in/2014/03/android-spannablestring-example.html
Here is an example:
final SpannableString text = new SpannableString("Hello World");
text.setSpan(new RelativeSizeSpan(1.5f), text.length() - "World".length(),text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new ForegroundColorSpan(Color.BLACK), 4, text.length() - 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(text);
https://developer.android.com/reference/java/util/Formatter.html
Please check above link for string formatting.
You can use Html.fromHtml() and format the string with HTML like;
String my_string = "<h1>MAIN TITLE</h1><br /><h2>SUBTITLE</h2><br />"
+"Detail 1 <br /> Detail 2 <br /><br/>"
+"<h4>Heading 1:</h4> User input data <br/>"
+"<h4>Heading 2:</h4> User input data"
Then
TextView myTextView = (TextView) findViewById(R.id.the_id_of_your_tv);
myTextView.setText(Html.fromHtml(my_string);

Bold characters in string.xml are not shown on screen

In my string.xml file, I have something like this:
<string name="example_string"><b>This</b> is a <b>%1$s</b></string>
And then I placed it into a TextView:
textView.setText(getString(R.string.example_string, "good question"));
The "good question" argument that I passed to the getString() method is not shown in bold. Even the word "This" is not shown in bold!
What's the reason for this and how to solve it?
=========================================================================
I know how to use Html.fromHtml(), but this method does not support inserting a string to the place holder that I have defined in the string resource. If you are trying to tell me that Html.fromHtml() exists, please DO NOT REPLY...
So after a day of search, I found the desired answer on Android Developers website! The Link to the page is here: https://developer.android.com/guide/topics/resources/string-resource.html
Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the String.format(String, Object...) method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place.
Basicaly, the change that I would make based on my original question is to replace the bracket "<" with the HTML tag for that, which is "&lt" + ";" (Type them together in your xml file! I had to separate them because StackOverflow will diplay the tag as the bracket itself.) For more detailed explanation, please see the Styling with HTML markup section from the website that I posted above.
i've had success using getText instead of getString. It seems to maintain styling.
from the docs:
You can use either getString(int) or getText(int) to retrieve a
string. getText(int) retains any rich text styling applied to the
string.
You need to format the text using Html.fromHtml or using a SpannableString.
Html.fromHtml example:
textView.setText(Html.fromHtml(getString(R.string.example_string, "good question")));
Edit:
If you're having trouble passing the tags through, its because it needs to be escaped by CDATA.
eg. <string name="example_string">This is a <![CDATA[<b>%1$s</b>]]></string>
Try this ..
String myString = "This is a " + "<b>" + "your_string" + "</b>";
textview.setText(Html.fromHtml(myString));
for more see here
Do like this below
String boldText = "Hello"+"<b>" + "StackOverflow" + "</b>";
textView.setText(Html.fromHtml(boldText));
Now your text look like this : Hello StackOverflow
See this link
use this... it will working.
/**
* Makes a substring of a string bold.
* #param text Full text
* #param textToBold Text you want to make bold
* #return String with bold substring
*/
public static SpannableStringBuilder makeSectionOfTextBold(String text, String textToBold){
SpannableStringBuilder builder=new SpannableStringBuilder();
if(textToBold.length() > 0 && !textToBold.trim().equals("")){
//for counting start/end indexes
String testText = text.toLowerCase(Locale.US);
String testTextToBold = textToBold.toLowerCase(Locale.US);
int startingIndex = testText.indexOf(testTextToBold);
int endingIndex = startingIndex + testTextToBold.length();
//for counting start/end indexes
if(startingIndex < 0 || endingIndex <0){
return builder.append(text);
}
else if(startingIndex >= 0 && endingIndex >=0){
builder.append(text);
builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0);
}
}else{
return builder.append(text);
}
return builder;

Any way to set span directly to spanable text?

This may be a blunder,But I need to know... :)
Iam develeoping an android application,In in I want to display two type face in a single textview and found this One very useful,A custom typeface span that extends typeface span,
As per my understanding , we are creating a spannable as follows using two words
String firstWord = "first ";
String secondWord = "second";
// Create a new spannable with the two strings
Spannable spannable = new SpannableString(firstWord+secondWord);
then sets two type face to that words using our custom span like this
// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0,
firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE), rstWord.length(), secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Now my question, I have a large amount of text so If i am able to put the spans directly in my text its will be a more easy for us ,is that possible to put spans directly to the text like we put <b>bold </b> as my need is to use my custom typeface span like <typeface1> sample </typeface1> <typeface2> Doc </typeface2>.
WHAT I NEED IS, DIRECTLY APPLY THE CHANGE TO TEXT WHAT THE SET SPAN DO TO THE TEXT
Is that possible, if possible what i need to write as span in my text,How can I achieve this.. or am i compleatly wrong ?
Thank you for all
Very late answer but what you asked for is pretty easy.
For instance, lets say we want to change everything between quotation marks into italic font.
String s = "\"Hello my name is Edward\" Hola, my nombre es Edward";
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(text);
Spannable spannable = new SpannableString(s);
while (m.find()) {
int textLocation = text.indexOf(m.group(1));
// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",my_italic_font),
textLocation-1, textLocation + m.group(1).length(),spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set the text of a textView with the spannable object
TextView textbox = (TextView) v.findViewById(R.id.cardtextbox);
}
textbox.setText( spannable );
Result of s would be
"Hello my name is Edward" Hola, my nombre es Edward
Now instead of quotation marks you would use a regex pattern for tags like <b>bold </b>;
And you could also remove the tags afterwards with a simple .replace();

Categories

Resources