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 .
Related
I have a webview with a bunch of images in it stacked vertically. When I run it on a nexus 6 emulator the scrolling works how I'd expect from my web-browsing on my phone.
However when I deploy the APK to my actual device, the scrolling behaves totally differently. It lags a bit behind my finger, and seems to have no inertia at all. This is on a Samsung s8+.
This is my current configuration:
String html = "<html><head><style>body {margin: 0; padding: 0; overflow: hidden;} img {}</style><body>" + imagesHTML + "</body></html>";
String mime = "text/html";
String encoding = "utf-8";
webView.getSettings().setBuiltInZoomControls(true);
// webView.getSettings().setSupportZoom(true);
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webView.setPadding(0, 0, 0, 0);
webView.setInitialScale(100);
webView.loadDataWithBaseURL(null, html, mime, encoding, null);
Any ideas?
I figured it out. Overflow: hidden; on the body was causing the weird behavior.
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", "");
I store Myanmar font in database. When I show Myanmar font by webview, They show the followings. How do I change my codes? Please help me.
ပရမá€á± (ပရမ + အá€á³) = အá‚ွစ္á€á€ºá€³á€•á€¹áŠ အျမင့္ဆုံး သá€á€…ရာá‹
These are my codes.
dstory = (WebView) findViewById(R.id.dstory);
String data=result.getString(3);
dstory.loadData(data , "text/html", "utf-8");
Try adding Fonts to your Asset folder and add it to your WebView by CSS
You Code Should be loaded from asset directory
webView.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
and your CSS should be
#font-face {
font-family: 'my_font';
src: url('my_font.ttf');
}
#Muthu Thank u for your advice.Now I got it.
In css file,
#font-face {
font-family: 'ZawgyiOne2008';
src: url('file:///android_asset/ZawgyiOne2008.ttf');
}
body{
font-family: ZawgyiOne2008; width: 100%;
background-color: transparent;
padding: 0px;
}
In my DetailActivity.java, to link css is used full html.
WebView view = (WebView)findViewById(R.id.webView1);
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html =
"<html><head><LINK href=\"file:///android_asset/bootstrap.css\" type=\"text/css\" rel=\"stylesheet\"/></head><body><H1 class='label'>A simple HTML page</H1>" +
"<input type='text' class='input-large' required='true' id='cname' name='cname'/>" +
"<input type='text'/>" +
"<p>The quick brown fox jumps over the lazy dog</p></body></html>";
view.loadDataWithBaseURL("", html, mimeType, encoding, "");
To show Myanmar Font from database, use string replace.
String old="%#";
String newstr=html.replace(old, data);
I want to display local html file on a WebView. (Android 2.3.3)
The HTML contains Hebrew text. I want the text to be justified, so in my css file I do the following:
body
{
text-align: justify; direction: rtl;
}
But for some reason the text end up being messed up:
And this is definitely not "justified" but more aligned to the left.
Any idea how can overcome this problem?
It's working perfectly fine on any other browser than the WebView. (Including WebKit based ones)
This code worked for me:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
String webtext = "שלום";
String summary = "<html lang=\"he\"><body><p dir=\"rtl\">" + webtext + "</p></body></html>";
myWebView.loadData(summary, "text/html", null);
}
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.