im working on an android app and im dealing with a webview inside of my android app. i have two layout mainly the activitymain.xml found in layout folder and another layout named activitymain.xml found in layout-land folder and im loading these two from 1 java file but i need these two to load two different webview one for landscape and one for portrait.my question is is it possible to directly put the url/file path of my webview in xml so that when the user change orientation and the activitymain.xml in layout-land load he load a webview for landscape and not the webview that is in portrait xml?
UPDATE:
i was able to run to it on my own terms problem is that it loads again from the start that was a stupid mistake i didnt put into account when the change occurs the app loads a new page which was the plan from that start but the problem is the data of the user before the change is lost and therefor i think that the solution i had is not a solution but a problem can you advice me on how to make change in orientation without the loss of data and to continue where in the last page where the change happened not to start from the beginning again ?
I think he is trying to find some way to set the url directly in the xml-file without having to run the method loadUrl in the Activity. Like: <Webview android:url="#string/my_url" />
But i dont think that is possible. See the official documentation Handling Runtime Changes
Changing it will actually create a new view.
Instead you can do it like this programmatically:
in your onCreate method code it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*getResources().getConfiguration().ORIENTATION_PORTRAIT;*/
webview = (WebView)findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient()
{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.facebook.com");
}
Furthermore you can check orientation change via:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
webview.loadUrl("http://www.google.com");
Toast.makeText(getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
webview.loadUrl("http://www.stackoverflow.com");
Toast.makeText(getApplicationContext(), "portrait", Toast.LENGTH_SHORT).show();
}
}
and put this in your manifest.xml <activity>
android:configChanges="orientation|screenSize"
Hopefully this will work for you. works fine for me.
Edit:
Dont forget to give the Internet Permission else it wont run
<uses-permission android:name="android.permission.INTERNET"/>
Else if any problem, then do let me know.
Thank you.
Related
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
when I load some data in web view many times that white page appears ...just scroll it the data is return back..Am notice this issues on android 4.x ...I test it in android 2.3.3 webview work fine
what I can do to prevent this issues ?
I am facing a similar issue and finally solved but I am not sure why. Things that make it work was:
1)
When I finish with a WebView onDestroy of activity/fragment I have:
#Override
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
if (myWebView != null) {
myWebView.destroy();
myWebView = null;
}
}
}
2)
I render the code via myWebView .loadDataWithBaseURL("file:///android_asset/", html_sourse, "text/html", "UTF-8", null); instead of myWebView.loadData(Uri.encode(html_sourse), "text/html", "utf-8");. When I am using the second line with an embedded css stylish inside html code page does not appear, changing to the first one (loadDataWithBaseURL) and adding to the html code a css from asset folder page appeared. I cannot understand why but works for me!
3) (optional)
Sometimes it is helpful to use clears if you do not care about keeping history:
myWebView.clearHistory();
myWebView.clearCache(true);
In my app there is an advertising web view, that is calling an url when the activity starts.
Everything is nice except one minor thing, it is more like a visibility issue...
So the thing is when i start the activity i literally see the page loading.. About in 0,3 seconds the texts appear then the pictures, and all the content somehow floating in from left to right. It not so nice, i would like to set the visibility of my webView to VIEW.GONE until it is done with the loading, and after that i could set it VISIBLE...
Is there a good, and working way for achieve this?
It is important that it is must work on Android 2.3 to 4.0 in each and every OS version.
I already tried onPageFinished and PictureListener related to this stack question here, but no hope, onPageFinished only works properly on 4.0 and PictureListener is for pictures which is not the best way to do this in case of different advertisings with different number of pictures. (and what if there is no picture at all...)
Please if you know a way let know with me. Thanks all.
have you tried WebChromeClient ?
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
// dismisses the PD
dismissLoadingDialog();
}
}
});
webView.loadUrl("your-Url");
// show message dialog here
createLoadingDialog();
i have used this on 2.3 to 4.0 OSes without any issue
Use webview visibility during onPageFinished method
view not display util all page loading.
webView1.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView1.setVisibility(View.VISIBLE);
}
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 ...
I am playing with an ap that has 2 webviews set up within a tabhost/tabwidget layout, my problem is that i don't know how to make them navigate back through page history, at least for both of them. I ca do it for the first webview (webview1) but i don't know how to do it for the second one in my second tab.
I know this question is ancient but you might still be stuck on it, or someone else might be. Use the code below, it works for me using tabHost. webView1 and webView2 being your two webviews.
Add it above the onCreate bundle.
public void onBackPressed(){
if (webView1.isFocused() && webView1.canGoBack()) {
webView1.goBack();
}
else {
//Add something you want to do, or leave blank to do nothing.
}
if (webView2.isFocused() && webView2.canGoBack()) {
webView2.goBack();
}
else {
//Add something you want to do, or leave blank to do nothing.
}
}