Tuesday, May 7, 2013

Set ViewPort of WebView

According to Android Developer document : The method WebSettings.setUseWideViewPort() tells the WebView to use a wide viewport. The default is false. And the method WebSettings.setLoadWithOverviewMode() sets whether the WebView loads pages in overview mode. The default is false.

It's not too clear for me. As my understanding, setUseWideViewPort(true) will try to make the WebView have a normal viewport as desktop browser, setUseWideViewPort(false) make the WebView have a mobile viewport of mobile for phone. setLoadWithOverviewMode(true) will loads the WebView in full zoomed out. In my testing, it's more or less depends on the target html.


WebView with WebSetting.setUseWideViewPort(true)

WebView with WebSetting.setUseWideViewPort(false)


package com.example.androidwebview;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

WebView myWebView;
//final static String myAddr = "http://android-er.blogspot.com";
final static String myAddr = "http://developer.android.com/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
myWebView = new WebView(this);

myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setLoadWithOverviewMode(true);

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.loadUrl(myAddr);
setContentView(myWebView);

}

private class MyWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

}

}


remark: uses-permission of "android.permission.INTERNET" is needed.

download filesDownload the files.

Next:
- Set user-agent string of WebView

No comments:

Post a Comment