Ok so what i do is the following:
i have a html string i show in a WebView like this:
webView.loadDataWithBaseURL("",htmlText, "text/html","utf-8", null);
i also have a local css file i want to apply to that html String in the webView.
i looked this up for a while but no solution seemed to work.
There should be a way to save the css file in the assets folder and call it from somwhere but i dont have an idea how.
and suggestions?
You can't write anything in the assets folder.
Since you have both the html and the css, I think you can insert css text into the head tag some how like this way
int pos = htmlText.toLowerCase().indexOf("</head>");
if(pos != -1) {
String newHtmlText = htmlText.substring(0, pos) + String.format("<style>%s</style>", cssText) + htmlText.substring(pos + "</head>".length());
webView.loadDataWithBaseURL("",newHtmlText , "text/html","utf-8", null);
}
disclaimer: untested :))
Since i didnt have a nor nor tag i just added them and put the style in the and my html-text in a like this:
String htmlWithCss = "<html><head><style type=\"text/css\">" +css +"</style></head><body>" + htmlText +"</body></html>";
and displayed it in the webView like this:
webView.loadDataWithBaseURL("", htmlWithCss, "text/html","utf-8", null);
This is just to show how to do it when you have blank html-formated text wothout tags around it. i will acceppt J.S. Taylor's answer nevertheless since it showed me basicly what to do.
Related
I'd like to filter an html String before loading it in a WebView:
I'd like to remove all the img tags with the param:
data-custom:'delete'
In example
<img src="https://..." data-custom:'delete'/>
How can I do this in Android in a elegant way (without external libraries if possible)
I'm going to go for a nice and simple:
String element = "<img src='https://...' data-custom:'delete'/>";
String attributeRemoved = element.replaceAll("data-custom:['|\"].+['|\"]", "");
Updated based on comment
If you want to remove the whole tag you can do this:
String elementRemoved = element.replaceAll("<.*data-custom:['|\"].+['|\"].*>", "");
If you only want to do it for <img> tags you can do:
String imgElementRemoved = element.replaceAll("<img.*data-custom:['|\"].+['|\"].*>", "");
A much more reliable way would be to parse the HTML as an XML document and use XPath to find all elements with a data-custom attribute and remove them from the document, then save the updated document. While you can do this stuff with regex, it's not normally a good idea...
I was hoping to get some help in how I should approach a program I have attempted to write a few times now.
I have a number of folders. In each folder, there is a HTML file, and a .txt file which contains text in the HTML file, stripped of all HTML tags.
As an example, a simplified HTML file may be
<html><head></head><body><p>This is some <b>text</b></p><p>Please ignore me</p></body></html>
And within a .txt in the same folder, I have "This is some text".
From these two files, I would like to create a new file which is a HTML with a box drawn around "This is some text", like so :
The obvious problem here is that the pretty-printed text files do not contain any mark-up, and so finding it within the HTML document is difficult.
My idea thus far has been :
-Save the .txt contents in a variable.
-Grab the HTML contents, strip of all HTML tags :
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
I'm unsure how to proceed from this point. I mean...I could try to add a div with a class surrounding the text, and then add a border style to this...but how do I find the sub-string in the HTML reliably, retaining all of the markup within the HTML ?
I'm sure there is a simple way to do this and I am just overthinking it, I would usually have a chat with a friend about this and solve it but everyone seems to be offline - so I come to you for guidance here.
Can anyone offer any feedback please? Thanks.
This should work for you:
More information on selectors and setting attribute values
private void test(){
//replace with your stored variables
String html = "<html><head></head><body><p>This is some <b>text</b></p><p>Please ignore me</p></body></html>";
String txt = "This is some text";
Document doc = Jsoup.parse(html);
String query = "p:contains(" + txt + ")";
Elements htmlTxt = doc.select(query); //selects all the paragraph elements with your target txt
//Loop through each element and add a red border around it
for(Element e : htmlTxt){
System.out.println("e: " + e.toString());
e.attr("style", "border:3px; border-style:solid; border-color:#FF0000; padding: 1em;");
}
}
I have some amount of informations to be displayed in Dialog Box. It comes like Title, then under it text; Title, then under it text. Like wise, there are 4 titles and 4 descriptions to be displayed. It should come like this
Title One
description;description;description;description;description;description;description;description;description;description;description;description;description;description;description
Title Two
description;description;description;description;description;description;description;description;description;description;description;description;description;description;description
As you can see, there are bold texts, underlined texts, line breaks etc. I want to add this kind of a text to the alert box, so below is what I tried.
TextView msg = new TextView(this);
msg.setText("<html><u>Message</u></html>")
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Title");
ab.setView(msg);
ab.setCancelable(false);
//rest of the code
However this trick didn't work. What happened is, all the HTML tags showed up as they are! And the text is not clear! Seems like it mixed with the background of the default colour of AlertBox, black. How can I solve this issue? Please help!
PS: Or am I using the wrong method? Wrong dialog box?
You will need to use Html.fromHtml() to use HTML tags in TextView as:
msg.setText(Html.fromHtml("<u>Message</u>"))
And you also see all HTML tags supported by TextView.
As it turns out, you don't actually need any extra TextViews to do this. Simply include the HTML in your alert's "setMessage()" call (which replaces the "setView()" call in your question) and pass it the html-formatted string. Be sure to only use <b>, <u>, and <i> in your formatting, though because those are the only tags it supports. If you're using a String resource for the text in your alert, call getResources().getText(R.id.yourHtmlString) rather than getResources().getString(R.id.yourHtmlString), though, or the tags will be completely stripped from the String.
If you want to add a link and make it clickable,
msg.setMovementMethod(LinkMovementMethod.getInstance());
msg.setClickable(true);
If you need to add more complex HTML, with CSS and META, you can add a WebView to the dialog, like this:
String webViewString = yourMeta + yourCss + yourHtml;
yourCustomWebView.loadData(webViewString, "text/html; charset=UTF-8",
null);
yourAlertDialog.setView(yourCustomWebView);
This way, you can display fully formatted HTML pages in your dialog.
Try this,
Font color,
String source = "<b><font color=#ff0000> Loading. Please wait..."
+ "</font></b>";
Font underline,
String source = <u>Message</u>
msg.setText(Html.fromHtml(source));
In case if you need it.
Better to use HtmlCompat.fromHtml((htmlString, 0) for compatibility with older versions.
I have a TextView that gets it's data set by calling this:
tv.setText(Html.fromHtml(myText));
The string myText contains partially formatted html data. For example, it might have font tags, but not have any url links formatted using <a href=...> tags. I was hoping to use the Linkify.addLinks(...) to do that since my text could include other types of links that Linkify would convert for me appropriately. So I wrote my code to look like this:
String myText = "<font color=\"red\">Red text</font> and Url: www.google.com";
tv.setText(Html.fromHtml(myText));
Linkify.addLinks(tv, Linkify.ALL);
tv.setMovementMethod(LinkMovementMethod.getInstance());
This does not work properly. Meaning that it processes the font tags but Linkify does not convert urls to UrlSpan properly.
Alternatively, if I call setText() without the Html.fromHtml(..), Linkify works but then I lose all the text formatted from the html font tags. Somehow they both seem to be conflicting and I can have only one or the other.
Now here's the interesting part that I dont understand. If I remove the Linkify code from java and go to my layout xml and put the following lines in there, all seems to be working (Linkify and fromHtml both end up playing nice together... somehow)
<TextView
...
android:autoLink="all"
android:linksClickable="true"
...
/>
Can someone explain to me why that would make everything work??
I looked into the source code for TextView's setMovementMethod() and it eventually ends up calling:
setFocusable(true);
setClickable(true);
setLongClickable(true);
That should theoretically make everything work and behave the same as the xml layout code. I tried switching the order of calling Linkify.addLinks(..) before setText(Html.fromHtml(..)) in the java code, but that didn't make a difference.
Any ideas as to why combining Linkify.addLinks() and Html.fromHtml() in java would cause this behavior... but not in the xml layout?
It's because Html.fromHtml and Linkify.addLinks removes previous spans before processing the text.
Use this code to get it work:
public static Spannable linkifyHtml(String html, int linkifyMask) {
Spanned text = Html.fromHtml(html);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, linkifyMask);
for (URLSpan span : currentSpans) {
int end = text.getSpanEnd(span);
int start = text.getSpanStart(span);
buffer.setSpan(span, start, end, 0);
}
return buffer;
}
You can try this one:
First set the text in to your TextView.
tv.setText(myText);
Convert the links with Linkify
Linkify.addLinks(tv, Linkify.ALL);
and finally replace the text with Html.fromHtml but using the Linkified text from your EditText.
tv.setText(Html.fromHtml(tv.getText().toString()));
100% works solution (kotlin).
Create class for store HtmlLink before Linkify
class HtmlLink(val urlSpan: URLSpan, val spanStart: Int, val spanEnd: Int)
Create spanned html (both formats for test)
val spanned = Html.fromHtml("https://google.com" +
"<br>Google")
Store html
val htmlLinks = ArrayList<HtmlLink>()
spanned.getSpans(0, spanned.length, URLSpan::class.java).forEach { urlSpan ->
htmlLinks.add(HtmlLink(urlSpan,
spanned.getSpanStart(urlSpan),
spanned.getSpanEnd(urlSpan)))
}
Create spannable builder and Linkify it
val builder = SpannableString(spanned)
Linkify.addLinks(builder, Linkify.WEB_URLS)
Restore spans.
htmlLinks.forEach { htmlLink ->
builder.setSpan(URLSpan(htmlLink.urlSpan.url), htmlLink.spanStart, htmlLink.spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
Set finally text
scrollContent.text = builder
I'm trying to download an image from the internet to show in a plugin. This plugin uses JEditorPane and contains html content. I have tried using a simple HTML code that would work in regular HTML:
imageUrl = "http://cactus.nci.nih.gov/chemical/structure/" + smiles + "/image";
builder.append("<img src=" + imageUrl + "alt=\"molecule image\"/></p>");
Of course, I found that this would not work. All I'm getting is a broken square where the image should be. I have looked on the internet and found that the HTMLFactory ImageView might work, but I cannot find how to implement it.
If anyone could help, that would be great:)
note: builder is a stringbuilder in which I store the html content for the jeditorpane.
http://java-sl.com/tip_local_images.html this could help