I was wondering if there is a way to get the html markup.
For example:
finalString = " <font color='#2caeac'>#test</font>";
editetext.setText(Html.fromHtml(finalString));
Now if I want to edit my edittext like this:
new_string = edittext.getText().toString(); // getting my "#test"`
new_string = new_string+"<font color='red'>newString</font>";
edittext.settext(Html.fromHtml(new_string));
Then my new_string doesn't catch the color of "finalString".
How is it possible to get the color of finalString?
I thought to a little tricky solution that involves the replace of tags in an HTML text.
The explanation is in code's comments.
String finalString = "<font color='#2caeac'>#test</font>";
textView.setText(Html.fromHtml(finalString));
// get the text with html
String new_string = Html.toHtml(textView.getText());
// the result will be something like <p dir="something">text_with_html_here</p>
// get the layout direction (above api 17 you can't use getDirection())
final int direction = Character.getDirectionality(Locale.getDefault().getDisplayName().charAt(0));
// check if it's RTL
boolean isRTL = direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT || direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
String layoutDirection = isRTL ? "rtl" : "ltr";
// replace raw tags added with toHtml()
new_string = new_string.replace("<p dir=\"" + layoutDirection + "\">", "").replace("</p>", "");
// use the String
new_string = new_string + "<font color='red'>newString</font>";
textView.setText(Html.fromHtml(new_string));
Related
I want to change text color before displaying it to TextView.
For example,I am getting a text from server like
<b>Pratik<b/> has shared photo with <b>you</b>.
Now the requirements are to display Pratik and you with Bold style and Blue text color. I tried several ways using <span> tag, but I am not getting clear way to display it.
String htmlBody = "<b>Pratik<b/> has shared photo with <b>you</b>.";
String formattedBody = "<span>" + htmlBody + "</span><style>b { color: #309ce8 ; } span {font-family: 'Avenir', 'Heavy'; font-size: 17; }</style>";
SpannableString text = new SpannableString(formattedBody);
tvMessage.setText(text, TextView.BufferType.SPANNABLE); // This is not working as expected.
tvMessage.setText(Html.fromHtml(htmlBody)); // This is not working as expected.
Help me achieve that.
String htmlBody = "<b style='color:blue !important;'>Pratik</b> has shared photo with <b style='color:blue !important;'>you</b>.";
Your Solution is:
String styledText = "<b><font color='red'>Pratik</font><b/> has shared photo with <b><font color='red'>you</font></b>";
You have to use like this
public void methodName() {
String html = "Some text <b>here</b>, and some <b>there</b>";
String result = html.replace("<b>","<font color=\"#ff0000\"><b>").replace("</b>", "</b></font>");
textView.setText(Html.fromHtml(result));
}
how can i set half bold text by html.fromhtml i try but didn't work in append of BufferString out append its work fine please help me here is code
String amt = "AMOUNT: ";
Spanned tyyy =Html.fromHtml("<b>"+"TYPE: "+"</b>");
String Dat = "DATE: ";
String des = "DESCRIPTION: ";
buffer.append(Html.fromHtml("<b>"+amt+"</b>"+"<small>"+cc.getString(cc.getColumnIndex("AMOUNT"))+"</small>")+"\n");
buffer.append(tyyy+cc.getString(cc.getColumnIndex("TYPE"))+"\n");
If it doesn't need to be from HTML, you can use SpannableStringBuilder:
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("TYPE:");
// bold the current text
int boldStartIndex = 0;
int boldEndIndex = bulder.length();
builder.setSpan(new StyleSpan(Typeace.BOLD, boldStartIndex, boldEndIndex, Spanned.FLAG_EXCLUSIVE_EXCLUSIVE));
// append the rest, it will not be bolded
builder.append("the-rest-of-your-data");
You can then set the builder directly to a TextView via TextView.setText(builder);. This may be a better approach than using HTML, as HTML tags support isn't very well documented and may not be supported across various devices.
HI everyone,
I have a bunch of text in an Edit text that I have set up to be styled(strike through only for the moment) using the setSpan method in Android. This seems to work fine.
The trouble I am having is that all the styling seem to get cancelled once I close that activity. That is when I load up the activity again , it just has plain text and none of the styling I had applied using the setSpan().
Note: All of my text get stored in a Database.
I have attached all the code for the styling, let me know if you need to see any more bits of code.
private void doStrick() {
int selectionStart = mBodyText.getSelectionStart();
styleStart = selectionStart;
int selectionEnd = mBodyText.getSelectionEnd();
// check for boo-boo's
if (selectionStart > selectionEnd){
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
Spannable str = mBodyText.getText();
str.setSpan(new StrikethroughSpan(),selectionStart, selectionEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
Is that some bit of code I need to be adding to save the styling?
EDIT based on answer:
Calendar cal=Calendar.getInstance();
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal);
float Textsize = mBodyText.getTextSize();
String title = mTitleText.getText().toString();
String body = Html.toHtml(mBodyText.getText());
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, date_time, Textsize);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, date_time, Textsize);
Log.d("MYTAG", "updateing note");
updateWidget();
And where I populate the fields:
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(Html.fromHtml(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))));
mBodyText = (EditText) findViewById(R.id.body);
float size = note.getFloat(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TEXT_SIZE));
mBodyText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
Is that some bit of code I need to be adding to save the styling?
Yes.
Presumably, right now, you are just saving thisIsYourEditText.getText().toString() to your database, then using thisIsYourEditText.setText(stringThatYouLoadBackOutOfYourDatabase) to populate the EditText.
Instead, you need to use Html.toHtml(thisIsYourEditText.getText()) to try to convert your styled text into HTML, and then use thisIsYourEditText.setText(Html.fromHtml(stringThatYouLoadBackOutOfYourDatabase)) to convert that HTML back into styled text.
Note that toHtml() and fromHtml() do not handle all possible CharacterStyles, nor are they guaranteed to do all of the styling correctly round-trip (i.e., the string generated by toHtml() may not match the string you started with before the fromHtml() call).
I have a String in TextView and I want to Linkify a substring from that string. for example:
click here to know more.
I'm getting the string dynamically. So i have to search if it has click here and convert that to link .How can I linkify "click here".
To find a pattern inside a text and replace it, use this:
Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
m.appendReplacement(sb, "click here");
result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();
yourTextView.setText(Html.fromHtml(strWithLink));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance())
This code will search inside your string and replaces all "click here" with a link.
And at the end, do NOT add android:autoLink="web" to you XML resource (section TextView), otherwise A-tags are not rendered correctly and are not clickable any longer.
did your tried like this
Click here
for setting it to textview
//get this thru supstring
String whatever="anything dynamically";
String desc = "what you want to do is<a href='http://www.mysite.com/'>"+whatever+":</a>";
yourtext_view.setText(Html.fromHtml(desc));
String urlink = "http://www.google.com";
String link = "<a href=\"+urlink+ >link</a>";
textView.setText(Html.fromHtml(link));
Raghav has the right approach using the fromHtml() method, but if you're searching for for a String with a fixed length, you could do something like:
String toFind = "click here";
if(myString.indexOf(toFind) > -1){
String changed = myString.substring(0, myString.indexOf(toFind)) + "<a href='http://url.whatever'>" + myString.substring(myString.indexOf(toFind), myString.indexOf(toFind) + toFind.length()) + "</a>" + myString.substring(myString.indexOf(toFind) + toFind.length());
}
else {
//String doesn't contain it
}
When setting the actual text, you need to use: tv.setText(Html.fromHtml(yourText)); or else it will just appear as a String without any additives. The fromHtml() method allows you to use certain HTML tags inside your application. In this case, the tag which is used for linking.
I am developing an application in which there will be a search screen
where user can search for specific keywords and that keyword should be
highlighted. I have found Html.fromHtml method.
But I will like to know whether its the proper way of doing it or
not.
Please let me know your views on this.
Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Using color value from xml resource:
int labelColor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!
Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE);
This can be achieved using a Spannable String. You will need to import the following
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
And then you can change the background of the text using something like the following:
TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Your text here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!
Alternative solution: Using a WebView instead. Html is easy to work with.
WebView webview = new WebView(this);
String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";
webview.loadData(summary, "text/html", "utf-8");
String name = modelOrderList.get(position).getName(); //get name from List
String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
/* check API version, according to version call method of Html class */
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText(context.getString(R.string._5687982) + " ");
holder.textViewName.append(Html.fromHtml(text));
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("123456" + " "); //set text
holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)); //append text into textView
}
font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")
To make part of your text underlined and colored
in your strings.xml
<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u></string>
then in the activity
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
and for clickable links:
<string name="text_with_link"><![CDATA[<p>text before linktitle of link.<p>]]></string>
and in your activity:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
First Convert your string into HTML then convert it into spannable. do as suggest the following codes.
Spannable spannable = new SpannableString(Html.fromHtml(labelText));
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));
It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.
Adding also Kotlin version with:
getting text from resources (strings.xml)
getting color from resources (colors.xml)
"fetching HEX" moved as extension
fun getMulticolorSpanned(): Spanned {
// Get text from resources
val text: String = getString(R.string.your_text_from_resources)
// Get color from resources and parse it to HEX (RGB) value
val warningHexColor = getHexFromColors(R.color.your_error_color)
// Use above string & color in HTML
val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"
// Parse HTML (base on API version)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
}
And Kotlin extension (with removing alpha):
fun Context.getHexFromColors(
colorRes: Int
): String {
val labelColor: Int = ContextCompat.getColor(this, colorRes)
return String.format("%X", labelColor).substring(2)
}
Demo