How do they load a url inside a webview instead of androids internal browser?
Add this line before the loadUrl()
call
bookingView.setWebViewClient(new WebViewClient());
This is the answer:
Features
- Load a URL on WebView
- Open another page in the website on Webview dont on local Browser.
- If you press on backbutton will go to the before page dont out of app.
MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
webView();
}
//Metodo llamar el webview
private void webView(){
//Habilitar JavaScript (Videos youtube)
webview.getSettings().setJavaScriptEnabled(true);
//Handling Page Navigation
webview.setWebViewClient(new MyWebViewClient());
//Load a URL on WebView
webview.loadUrl("http://stackoverflow.com/");
}
// Metodo Navigating web page history
@Override public void onBackPressed() {
if(webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
// Subclase WebViewClient() para Handling Page Navigation
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("stackoverflow.com")) { //Force to open the url in WEBVIEW
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Include this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webview" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
RESULT
START PAGE
ANOTHER PAGE IN THE WEBSITE ON WEBVIEW