How To Display Webview In Android
Hello everyone, in this post I will discuss how to display a website using WebView on Android Studio.
Okay, as usual for a new project, then open activity_main.xml and enter the following code to define the WebView component.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</WebView>
</RelativeLayout>
Then, open MainActivity.java then enter the following code to define the WebView component and then display our website.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyBrowser());
view.loadUrl("http://www.tutscode.net");
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Until here, we have finished the process of displaying the website, but when we enter the pages of the website then press the back button, then the application will exit. It should return to the previous page.
To prevent this, enter the following functions under the MyBrowser function
public boolean onKeyDown(int keyCode, KeyEvent event) {
//when touched by the back button
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack(); //method goback(),to return to the previous page
return true;
}
// If no page has been opened
// it will exit the activity (close the application)
return super.onKeyDown(keyCode, event);
}
And finally, enter permission to access the internet on AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
When it's finished, the program is ready to run