I've looked through dozens of pages if similar questions, none of them have any answers, so hopefully this one will be different.
I have a webview, and I do not want the zoom of the view to change from the initial zoom level I have it set to. The only thing which changes the zoom level currently is when a text box is focused.
I need to be able to do this through Java code, not using the viewport meta tag.
Just so I don't have the common responses, I have the following in my code to disable zooming, and the zoom controls:
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportZoom(false);
I'm thinking that a possible solution is to check to see when an onFocus or even an onClick event occurs within the WebView and then zoomOut, but I'm not even sure if that is possible?
Any suggestions would be appreciated.
UPDATE This answer was written almost 6 years ago, with all the new android versions that came since then, this is most likely outdated.
This thing caused a major headache, but finally was solved thanks to setDefaultZoom(ZoomDensity.FAR);
One thing which is important is that onCreate and loadUrl get called before the WebSettings, otherwise it caused a force close situation. Here the ENTIRE code including imports (for the novice Java users)
package com.my.app;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebSettings.ZoomDensity;
import com.phonegap.*;
public class MyDroidActivity extends DroidGap {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
WebSettings settings = appView.getSettings();
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDefaultZoom(ZoomDensity.FAR);
}
}
I solved this on HTC phones by adding a WebViewClient with an empty listener for onScaleChanged. My app is PhoneGap, so this is what it looks like, but adding the listener should look the same in a non-PhoneGap app:
public class Main extends DroidGap {
private class NoScaleWebViewClient extends GapViewClient {
public NoScaleWebViewClient(DroidGap ctx) {
super(ctx);
}
public void onScaleChanged(WebView view, float oldScale, float newScale) {
Log.d("NoScaleWebViewClient", "Scale changed: " + String.valueOf(oldScale) + " => " + String.valueOf(newScale));
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.init();
setWebViewClient(appView, new NoScaleWebViewClient(this));
// disables the actual onscreen controls from showing up
appView.getSettings().setBuiltInZoomControls(false);
// disables the ability to zoom
appView.getSettings().setSupportZoom(false);
appView.getSettings().setDefaultZoom(ZoomDensity.FAR);
appView.setInitialScale(100);
}
}
Strangely, the onScaleChange listener never gets called -- by listening for the zoom, it blocks the zoom from happening. I've found that I need all the other calls (setSupportZoom, setDefaultZoom, setInitialScale) in order for this to work, and removing any of them reverts to the old, buggy behavior.
I had the same trouble. I needed to find a way to scale content of webview to exact value, everything worked fine until user starts to input text. There are methods that work on relatively new devices android 4.0+ but fails on old ones. The only way that works everywhere is setting the zoom value not in Java but in viewport like this
<meta name="viewport" content="initial-scale=.80; maximum-scale=.80; minimum-scale=.80;" />
It works on every device I tested.
Did you try to disable the user-scalable in the viewport tag? Not sure if that will work for you, but it works for me. I did not need to do anything on the java side.
<meta name="viewport" content="user-scalable=no, width=device-width" />
I have encountered this problem too, and I solved it like this:
myWebview.getSettings().setDefaultZoom(ZoomDensity.FAR);
It's runing normally on Sumsung Galaxy Tab. I hope this will help you.
The WebView has one special "thing", which I think it will trigger many questions and answers here. What happens is, that when an URL is loaded, the default Android Browser kicks in through an Intent to handle this. The zooming takes part in this browser, not in your Webview.
Solution: You need to add a WebviewClient to tell Android that you handle the browsing yourself. An example:
// Use WebView and disable zooming
public class MyWebView extends Activity {
// nested class
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true
}
}
private WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setInitialScale(500); // added after user comment
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportZoom(false);
mWebView.loadUrl("http://www.google.com");
}
}
My main.xml looks like this
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
This code disabled zooming on my HTC Desire running Android 2.2. Tapping into HTML Input fields makes no difference.
The whole topic of WebView/HelloWebViewClient as well as an important hint to handle the "Back" button correctly is documented in Hello Views, Web View. It should be required reading for anybody who uses WebView.
I believe you can set the zoom level with WebView.setInitialScale method. It takes an int as scale so I guess you would want to do something like myWebView.setInitialScale(100).
This issue has been fixed by a firmware update on HTC devices, it was (apparently) being caused by the Sense UI overriding default Android functionality incorrectly.
It is very difficult to provide information on exactly when this was corrected, however my web application no longer zooms when a text box is clicked on any HTC device with the latest firmware.
The following two lines of code will disable the "zoom" aspects of an android webview:
// disables the actual onscreen controls from showing up
mWebView.getSettings().setBuiltInZoomControls(false);
// disables the ability to zoom
mWebView.getSettings().setSupportZoom(false);
This was headache for me too, but fortunately I have found this article: How to stop zoom in on input focus on mobile devices.
Set font size of the text in the input element to 16px (or more) in the css file.
input {
font-size: 16px;
}
It is rather hack, but if nothig else works ...
Related
Below is the WebView code, which shows the webpage at here. Everything works fine. The date picker is so slow, everything else works fine. It takes like 4-5 seconds to select a date. Any alternatives?
public class click extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.click);
WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.exceptnothing.com/appointment.html");
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
}
I tried adding android:hardwareAccelerated="true" in that activity, same effect still.
I'm a beginner, so simpler code will be appreciated. Thanks in advance :)
try to checkout android DatePickerDialog. Its native and fast way to pick a date on android. Also, using webview in android applications is a bad practice to build a well formed user interfaces, it's realy decreases the application performance, look, and user feel. Native android vidgets are always best to do the work. This tutorial will help you if you decide to build your ui as views layout http://www.tutorialspoint.com/android/android_datepicker_control.htm
I have a very basic Android app in Google's Play store. It's basically one window with a webview showing local html content. Most users who download the app have no problems with it. However, a few are not able to use it at all. When they try to open it, they get a warning "The file must have been renamed, moved, or deleted". In other words their phone or tablet can't locate the html files that are packaged together with the app. I can't replicate this problem and have no idea where it's coming from. I wonder if anyone here run into this issue before and resolved it.
For reference, the app design is shown below (nothing special). A bunch of "htm" files is located in "assets". One of them is referenced in the code explicitly - "Contents.htm". There's no css or javascript, but it didn't seem to make any difference as far as this particular error is concerned. This problem is experienced by people outside the US (so far), which may be another clue as to what it could be.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</WebView>
MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl("file:///android_asset/Contents.htm");
}
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
One of my users finally traced the problem to the app called WPS office. Indeed, when WPS office is installed on a device, my app stops working. Apparently WPS hijacks internal links within android webviews and tries to open them by itself. There are no obvious settings to change that behavior, but after uninstall everything returns to normal. I hope this bit of information may be helpful to someone someday.
Try this.
WebView browser = (WebView) findViewById(webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebChromeClient(new WebChromeClient());
browser.loadUrl("file:///android_asset/www/index.html");
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
I found the solution:
WPS office hijacks all links in any webview. You can build a workaround like this:
Write a Javascriptinterface and every link should call a Android-Function which load the specific Webview-Url
#JavascriptInterface
public void startGame() {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("file:///android_asset/www/game.html");
}
});
}
With this workaround everything works fine: You can test the workaround in my app
https://play.google.com/store/apps/details?id=de.devbert.circlecommander
I'm using the API 17 emulator to test a page containing a web view.
The webview first loads a page using the GET method.
Then the user submits the web form using HTTP POST method which causes a second page to load.
At this point if I rotate the screen I receive the "Webpage not available" error seen below. This only occurs if the page was loaded using the POST method. Note: I'm trying to restore the webview's state using webview.restoreState (see code below). Is there any way to tell Android to re-post the form data and reload the page instead of displaying this error message?!
I can't reproduce this same issue on KitKat, Lollipop, or Gingerbread... I can only reproduce this issue on Jellybean and Ice Cream Sandwich so far...
I've also confirmed this is an issue on an actual Nexus 7 device running Jellybean, so it's not an emulator-only problem.
Note: I'm not particularly interesting in using something like android:configChanges="orientation|keyboardHidden". As I understand it, this might solve my rotation issues, but the problem may still resurface if the activity state needs to be restored for other reasons.
Screenshots:
Step #1: Load the WebView Normally
Step #2: Submit the Form (uses HTTP Post Method)
Step #3: Rotate the screen to trigger webview.restoreState - error occurs
Code:
Here is some sample code to go along with my question. The code is in Mono C# but should be very nearly identical to Java.
public class MainActivity : Activity
{
WebView webview;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
webview = new WebView(this);
SetContentView(webview);
if (bundle == null)
webview.LoadUrl("http://2-dot-npwc-services.appspot.com/test-post.jsp");
else
webview.RestoreState(bundle);
}
protected override void OnSaveInstanceState(Bundle bundle)
{
base.OnSaveInstanceState(bundle);
webview.SaveState(bundle);
}
}
The sample HTML page that is performing the POST method looks like this:
<html>
<form action="test-post.jsp" method="post">
<input type="text" name="test" value="test"/>
<input type="submit"/>
</form>
<p>You entered: <%=request.getParameter("test")%></p>
</html>
The browser it's doing good (although it's a pain for us), you have 2 ways:
1- Keeping the webView instance and restoring the state, adding like you said android:configChanges="orientation|keyboardHidden"
2- Or reloading the post petition again.
I take the first one and if i get some error, i will go back to the last page. Doing static content, so on rotation no network or a new petition it's needed on each rotation, which if not, on server side will be a pain too.
To achieve the "if error go back" you need to set a Custom WebClient and override this method
webview.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
if ( webView.canGoBack() ) {
Toast.makeText(MainActivity.this, R.string.error_web, Toast.LENGTH_SHORT).show();
webView.goBack();
}
}
});
You can filter by errorCode to go back when you want, in some kind of error you can go back on other do other thing. I dont' know which error raises this POST request or if you want more filter on other situations, so i'm sure you can do a fine grain filter using it.
Edit: You have here the possible error codes
WebViewClient Error Codes
I hope this helps.
My application is a simple web view type of app. It just loads a website in one page but I'm having a font issue where on some devices some languages are not supported, is there any solution for this situation?
My code is below:
public class MainActivity extends Activity {
private WebView web1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web1=(WebView)findViewById(R.id.web);
web1.getSettings().setJavaScriptEnabled(true);
web1.setWebViewClient(new WebViewClient());
web1.getSettings().setBuiltInZoomControls(true);
web1.loadUrl("http://dcs-dof.gujarat.gov.in/live-info.htm");
}
First please make sure the charset attribute is correctly set in HTTP header or the meta field of the HTML page.
Besides, and the displaying may also depend on the fonts pre-loaded on the specific devices. Although by default most languages are supported in Android AOSP, but as far as I known some manufacturers will remove some characters/languages just in order to save up the disk spaces.
To tackle #2, A tricky way is to install/copy the fonts manually to your device under /system/fonts.
I've run into a problem when using <input type="password"> fields in a WebView on Honeycomb devices. Any time the view is scrolled, the screen flickers black and can even stay all black (except that it will draw the focused password field) once scrolling ends. I've seen this on all three Honeycomb tablets I've checked.
I can load the same HTML in the Browser app and I do not see this issue. I've tried changing many of the settings on the WebSettings/WebChromeClient/WebViewClient of the WebView and had no luck there. I've loaded the code below on a Froyo tablet and this issue did not occur, so it seems like a Honeycomb specific issue.
Has anyone seen this before? I'm at a loss on how to fix or workaround this issue currently.
Here's a short code sample that reproduces the issue. Simply focus the password field and scroll up and down. There's a password type input field and a text type input field, just to show that the issue does not occur with the text type field. The <div> tag is there simply to make it easier to scroll around and see the issue, although the issue still occurs without the <div> tag.
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class PasswordFieldTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
String html = "<html><body><div style=\"with: 120%; height: 200%; border: 20px dashed black;\">" +
"Password: <input type=\"password\" name=\"passfield\"/><br/>" +
"Text: <input type=\"text\" name=\"textfield\"/>" +
"</div></body></html>";
webview.loadData(html, "text/html", "utf-8");
setContentView(webview);
}
}
After trying everything suggested here, this finally worked for me on all the phones:
android:hardwareAccelerated="true"
AND:
if (android.os.Build.VERSION.SDK_INT < 16) {
webView.setBackgroundColor(0x00000000);
} else {
webView.setBackgroundColor(Color.argb(1, 0, 0, 0));
}
Please let me know if you find a phone this doesn't work on.
Works with these phones:
note2 (4.1.2)
htc one x (4.0.4)
galaxy s3 (4.3)
nexus4 (4.3)
This is a known issue in honeycomb devices.
However this one worked for me -
Compatibility.getCompatibility().setWebSettingsCache(webSettings);
Make sure to implement a Compatibility layer, since following method doesn't work in SDK_INT < 11.
webViewInstance.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
List of solutions suggested are here.
This sounds like a android:cacheColorHint issue. Try setting it to transparent in the WebView's attribute set.
For me android:layer="software" in the xml layout file works fine.