I am working on a reader and I have an issue with latest generation of android devices which comes with high resolution. The pictures on webViews are showing very small, while on older devices their size seemed acceptable. I cannot manipulate the content of the HTML files, I can only manipulate the webView's settings and the .css file linked to the webView.
Initially when I open the book the image shows very small, but when I manipulate the image it gets over magnified and becomes trimmed in both sides.
img
{
max-width: 100%;
width:auto;
height: auto;
}
I also tried:
img
{
min-width: 100%;
height: auto;
}
This is the webView settings:
testWV = (WebView) findViewById(R.id.mywebview1);
testWV.setDelegate(this);
testWV.setVerticalScrollBarEnabled(false);
testWV.setHorizontalScrollBarEnabled(false);
testWV.getSettings().setDefaultZoom(ZoomDensity.FAR);
Okay, try this, you may remove the head tag if you wish, the style is the important part
String content = "Your Content"; // I assume your content is a string
testWV = (WebView) findViewById(R.id.mywebview1);
testWV.setDelegate(this);
testWV.setVerticalScrollBarEnabled(false);
testWV.setHorizontalScrollBarEnabled(false);
testWV.getSettings().setDefaultZoom(ZoomDensity.FAR);
String head = "<head><meta name='viewport' content='target-densityDpi=device-dpi'/></head>";
String style = "<style> " +
"img { height:auto !important; width:100% !important; } " +
"</style>";
testWV.loadDataWithBaseURL("", head + style + content, "text/html", "UTF-8", "");
Related
I have an app which takes data from a database and then displays it as a list of articles. The data is taken and put in a recyclerView with web views in it.
One specific article has this html:
<div style="position: absolute; height: 100%; background: url('https://www.softray.it/wp-content/uploads/2015/10/home-test-6.2.png') no-repeat;">
<div style="height: 100%; width: 50%; margin-left: auto; margin-right: auto;display: table-cell; vertical-align: middle; text-align: center;">
<h1 style="padding: 10px; text-align: center; font-family: 'Open Sans', sans-serif; color: #ffffff;">SOFTRAY TECHNOLOGY</h1>
<p style="padding-left: 5px; text-align: center; color: #ffffff; font-family: 'Open Sans', sans-serif;">La potenza del mobile re-inventa le applicazioni business e un nuovo stile di IT</p>
</div>
</div>
*Sorry for the messy html I just don't have a decent editing tool on the database.
The problem here is that my background image doesn't display and even the second div doesn't center vertically the way it should.
I tried to attach html and body tags to my data before displaying it but still no background image loads.
holder.webView.loadData("<html style='height:100%;'><body style='height:100%;margin:0;padding:0;'>" + s + "</body></html>", "text/html", "utf-8");
I know I probably have to give an element a fixed height but I want to adapt to any screen. Any tips?
EDIT:i just need to get the height in pixels of the webview content so I can set that in the html tag.
Problem with this is that I need to know this dimension before I load my data.
Try saving the html code as example.html file in the assets folder and then load the web view using :
webView.loadUrl("file:///android_asset/example.html");
The web view shall use match_parent as width and height to cover 100% of its parent layout.
Edit:
On getting the data from server, you can implement this method:
private void saveHtmlFile(String htmlStr) {
String path = "/data/data/" + getApplicationContext().getPackageName() + "/files/";
String fileName = "example";
fileName = fileName + ".html";
File file = new File(path, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
byte[] data = htmlStr.getBytes();
out.write(data);
out.close();
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///data/data/" + getApplicationContext().getPackageName() + "/files/example.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Kindly check this link once:
https://stackoverflow.com/a/15617341/6388699
Hello i have this html from webservices and i load it into web view ,, its working good ,, now i need to add my font to this , and make its gravity right !
BodyNot = "<html> <head> <style> body { background-color: clear !important; } p,div,span,li { color:black; font-size:17px !important;background-color: clear !important;} embed, iframe, object, video {height: 160px; width: 355.0px;} img { height: 160px; width: 355.0px; } </style> </head> <body><p>" +
BodyNot +
"</p>" +
"</div></p></body> </html>";
serviceWebView.loadData(BodyNot, "text/html; charset=utf-8", "UTF-8");
serviceWebView.getSettings().setBuiltInZoomControls(true);
serviceWebView.getSettings().setDisplayZoomControls(false);
I'm a little bit guessing but I think that changing <p> to <p align="right"> will do the job.
I create a service that loads data from a remote server and returns HTML data. This data I put to my WebView. All work good but have one problem: If some word is too long, WebView adds horizontal scroll. I add CSS file with break-work, word-wrap but it doesn't help.
JSONObject jsonObject = new JSONObject(strResult);
String content = jsonObject.getString("postContent");
TextView postTitle = (TextView) view.findViewById(R.id.postTitle);
postTitle.setText(jsonObject.getString("postTitle"));
WebView postContent = (WebView) view.findViewById(R.id.postContent);
postContent.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
postContent.getSettings().setLoadWithOverviewMode(true);
postContent.getSettings().setUseWideViewPort(true);
postContent.getSettings().setBuiltInZoomControls(true);
postContent.getSettings().setJavaScriptEnabled(true);
postContent.loadDataWithBaseURL("file:///android_asset/", content, "text/html; charset=utf-8", "utf-8", null);
I did face completely similar problems and finally realized that I misused the css options for that. Just add word-break: break-all; word-break: break-word to css style for body and/or headers and it's done
<head>
<style type="text/css">
body {text-align: center; word-break: break-all; word-break: break-word}
h1 {font-size:large; word-break: break-all; word-break: break-word}
h2 {font-size:medium; word-break: break-all; word-break: break-word}
</style> </head>
Some more details for css properties can be found here or there
Please be careful, as word-break option could seriously impact the readability of the text in WebView. Only use it when you really need it.
Apparently:
setLoadWithOverviewMode(true) loads the WebView completely zoomed out
setUseWideViewPort(true) makes the Webview have a normal viewport (such as a normal desktop browser), while when false the webview will have a viewport constrained to its own dimensions (so if the webview is 50px*50px the viewport will be the same size)
so i recommend you don't use setUseWideViewPort, the following code is for similar task that worked good:
final WebSettings webSettings = webView.getSettings();
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setEnableSmoothTransition(true);
webView.setBackgroundColor(Color.parseColor("#00000000"));
String before = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/fonts/w_yekan.ttf\")}body {font-family: MyFont;font-size: 14px;text-align: right;}</style></head><body><div style=\"direction:rtl !important;; text-align:right !important;\">";
String after = "</body></html>";
String myHtmlString = before + Utils.editString(DoaText) + after;
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
webView.loadDataWithBaseURL(null, myHtmlString, "text/html", "UTF-8", null);
i hope this answer be a good solution for you .
I need to change webview font face , I've searched and I used this but it didn't change the font , I've the font file in asset folder :
wb.loadData(
"<html><head><style>#font-face { font-family: myface;src: url('file:///android_asset/yekan.ttf');" +
"BODY, HTML {background: transparent; } body,div { font-family: myface;} </style></head><body><div style='text-align: justify; line-height: 23px;float:right' dir='rtl'>"
+ text + "</div></body></html>",
"text/html; charset=utf-8", "UTF-8");
is it wrong or webview couldn't change the font face ?
thanks
change
url('file:///android_asset/yekan.ttf')
to
url(\"file:///android_asset/yekan.ttf\")
In some web browsers, huge images are automatically resized to fit the screen.
Is it possible to do the same in an Android WebView?
The web page just contains the image, maybe adding some JavaScript could do the trick?
Anybody has already done this?
Note: I don't know the size of the image in advance.
Yes, it's possible. You can try setting the WebView Layout using the code below. It resizes all Images (Greater than the Device Screen Width) to the Screen Width. This works for both Orientations (Portrait and Landscape)
webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
You can add extra margins/padding later to get the spacing right.
webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
works but is deprecated. This is another solution without LayoutAlgorithm.SINGLE_COLUMN, using CSS:
#SuppressLint("NewApi")
private openWebView() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.TEXT_AUTOSIZING);
} else {
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
}
String data = "<div> your HTML content </div>";
webView.loadDataWithBaseURL("file:///android_asset/", getHtmlData(data), "text/html", "utf-8", null);
}
private String getHtmlData(String bodyHTML) {
String head = "<head><style>img{max-width: 100%; width:auto; height: auto;}</style></head>";
return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
}
You could use this:
WebView webView = (WebView) findViewById(R.id.myWebView);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
Found this solution here:
How to set the initial zoom/width for a webview
You can have the browser resize the image for you to fit the maximum width of the screen:
<img src="huge-image.jpg" width="100%" />
Resizing its height to WebView's viewport is possible too:
<img src="huge-image.jpg" height="100%" />
However, resizing both width and height would result in a stretched image. To either resize the width or height depending of what side fits best you may consider a bit of JavaScript, like this:
<img src="huge-image.jpg" onload="resize(this);" />
<script type="text/javascript">
function resize(image)
{
var differenceHeight = document.body.clientHeight - image.clientHeight;
var differenceWidth = document.body.clientWidth - image.clientWidth;
if (differenceHeight < 0) differenceHeight = differenceHeight * -1;
if (differenceWidth < 0) differenceWidth = differenceWidth * -1;
if (differenceHeight > differenceWidth)
{
image.style['height'] = document.body.clientHeight + 'px';
}
else
{
image.style['width'] = document.body.clientWidth + 'px';
}
// Optional: remove margins or compensate for offset.
image.style['margin'] = 0;
document.body.style['margin'] = 0;
}
</script>
I faced the same problem and used Jsoup to help me out and add the required respected CSS. You can easily add attributes or CSS. I my case, I download from many sources various different HTML files, save them and then display them in a Webview. Here is how I parse the HTML before I save it to the database with Kotlin:
// Parse your HTML file or String with Jsoup
val doc = Jsoup.parse("<html>MY HTML STRING</html>")
// doc.select selects all tags in the the HTML document
doc.select("img").attr("width", "100%") // find all images and set with to 100%
doc.select("figure").attr("style", "width: 80%") // find all figures and set with to 80%
doc.select("iframe").attr("style", "width: 100%") // find all iframes and set with to 100%
// add more attributes or CSS to other HTML tags
val updatedHTMLString = doc.html()
// save to database or load it in your WebView
Add Jsoup to your project
Have fun!
If your WebView width is fill_parent then you can use this code:
Display display=getWindowManager().getDefaultDisplay();
int width=display.getWidth();
String data="<img src='http://example.com/image.jpg' style='width:"+width+"px' />";
webView.loadData(data, "text/html", "utf-8");
And zoom still working!
Same method if height is fill_parent.
My favorite's :
String data = "<html><body ><img id=\"resizeImage\" src=\""+PictureURL+"\" width=\"100%\" alt=\"\" align=\"middle\" /></body></html>";
webview.loadData(data, "text/html; charset=UTF-8", null);
You could send the size you want in the request parameters and let the server set the width/height in the img element for you.