A WebView lets you pull a web page and display it in your Android app. It doesn’t take long to implement an Android WebView. Read on. I’ll show you how.
AndroidManifest.xml
First, open your manifest file to add this permission for INTERNET:
1 |
<uses-permission android:name="android.permission.INTERNET" /> |
The web page won’t be loaded into your app without this permission.
This is how my manifest file looks like:
Path: ...\MyAndroidStudioProjects\WebView\app\src\main\AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.catzie.webview" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
activity_main.xml
Then we’re adding a WebView element to the XML file. My XML file is named activity_main.xml
Path: ...\MyAndroidStudioProjects\WebView\app\src\main\res\layout\activity_main.xml
1 2 3 4 5 6 |
<?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" /> |
MainActivity.java
I have MainActivity.java
here, which loads activity_main.xml
and then loads a web page (google.com) into the WebView
.
Path: ...\MyAndroidStudioProjects\WebView\app\src\main\java\net\catzie\webview\MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package net.catzie.webview; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class MainActivity extends Activity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * WebView Begin */ webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.google.com"); } } |
The following line of code attaches the WebView whose id is “webview” to the variable “webView”:
1 |
webView = (WebView) findViewById(R.id.webview); |
And this allows JavaScript in the WebView
:
1 |
webView.getSettings().setJavaScriptEnabled(true); |
This one is what actually loads a given URl into the WebView
:
1 |
webView.loadUrl("http://www.google.com"); |