How To Open Web Page Within My App? - android

This is my first question here. I know that this question has been asked before, but I didn't find an answer/solution that really explains the answer for a totally newbie like me.
I am creating an app with a linear layout that has a lot of buttons, each button should drive the user to a different web page. The buttons works well and every buttons goes to its specific web page, but in the default browser, not within the app.
This is my webview.xml file:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
This is the WebViewActivity.java file:
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(
"http://egy-tech-droid.blogspot.com.eg/search/label/%D8%AA%D8%B7%D8%A8%D9%8A%D9%82%D8%A7%D8%AA%20%D8%AD%D8%B5%D8%B1%D9%8A%D8%A9");
}
I added the internet permission in the Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
This opens the web page but in the default browser of the device and I want it to open inside my app. Any help? (please give me a detailed answer/explanation)

Add this to your code
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});

You need to set up a WebViewClient in order to override that behavior (opening links using the web browser).
Use this;
webview.setWebViewClient(new WebViewClient());
Android documentation says:
public void setWebViewClient (WebViewClient client)
Sets the WebViewClient that will receive various notifications and
requests. This will replace the current handler.

Enjoy full code :
Oncreate () :
webView = (WebView) findViewById(R.id.webView1);
if(Constants.isNetworkAvailable(mContext)){
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new WebChromeClient() );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.setInitialScale(30);
webView.loadUrl(url);
}else{
Toast.makeText(mContext, Constants.msgNoInternet, Toast.LENGTH_LONG).show();
}
MyWebViewClient :
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if (!pDialog.isShowing()) {
pDialog.show();
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//view.loadUrl(url);
System.out.println("on finish");
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}

Kotlin version of Sunny's answer
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return true
}
}

You can't talk about the Web nowadays without considering Javascript. By default, its use in a WebView is not active. To enable Javascript just insert these lines of code:
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

I hope this will help you.
In your web view layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#c7bbac">
<ImageView
android:id="#+id/txtmain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/topbar50" />
<ImageView
android:id="#+id/backbutn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:adjustViewBounds="true"
android:paddingTop="2dp"
android:src="#drawable/backbtn" />
</RelativeLayout>
<WebView
android:id="#+id/webView1"
android:layout_below="#+id/relay"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Webview Button Onclick:
webbutton = (ImageView) findViewById(R.id.web);
webbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
startActivity(intent);
}
});
Webview Activity:
public class WebViewActivity extends Activity {
private WebView webViewurl;
ImageView back;
AndroidInterface AMW = AndroidInterface.GetInstance();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
back = (ImageView) findViewById(R.id.backbutn);
webViewurl = (WebView) findViewById(R.id.webView1);
webViewurl.getSettings().setJavaScriptEnabled(true);
webViewurl.getSettings().setBuiltInZoomControls(true);
final Activity activity = this;
webViewurl.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
webViewurl.loadUrl("http://example.com");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}

webView = (WebView) findViewById(R.id.youtubelink);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("your url");
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.google.co.in");
this code works fine...
Above code opens the link in your App.

Related

display google forms in webview using android studio

I'm trying to open a google form in a WebView.
I write the form in English but when I embed it in my app the page displays in Arabic(?) and the text goes from the right to the left. Why?
my xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.webview.feedback">
<WebView
android:id="#+id/link_webview"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Java
public class Feedback extends AppCompatActivity {
private WebView feedbackformlink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
setTitle("Your Feedback");
feedbackformlink = (WebView)findViewById(R.id.feedback_webview);
WebSettings webSettings = feedbackformlink.getSettings();
feedbackformlink.setInitialScale(200);
feedbackformlink.getSettings().setSupportZoom(true);
feedbackformlink.getSettings().setLoadWithOverviewMode(true);
feedbackformlink.getSettings().setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
feedbackformlink.loadUrl("https://google form .. share link");
feedbackformlink.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed() {
if (feedbackformlink.canGoBack()){
feedbackformlink.goBack();
} else
super.onBackPressed();
}
}
Apply this below code inside OnCreate Method of Activity! No need to use Any Tag of WebView in XML.
Hope it works.
..........................
WebView mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#TargetApi(android.os.Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("https://docs.google.com/forms/ ... link");
setContentView(mWebview );

How Can I Continue Internet Link Action With My App?

I have a webview. My question is, when user clicks to a link in webview, how to continue with my app?
When user clicks to a link, this dialog box appearing:
How can I avoid this dialogbox and continue with my app?
WebView Code:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(url);
Edit (MYActivity İn Test project)
package com.mycompany.myapp5;
import android.app.*;
import android.os.*;
import android.webkit.*;
public class MainActivity extends Activity
{
WebView view;
String url="http://google.com";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
}
}
This SO answer is exactly what you need.
The idea is to set a WebViewClient to your WebView and override shouldOverrideUrlLoading method like below:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
I hope this helps you!
Here is the complete code from a test project that is running.
The xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.test.myapplication.MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</RelativeLayout>
Code in the Activity:
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
String url="http://www.google.com";
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl(url);
}
This works fine in a 4.4 device. Please try this and let me know if you still have the issue.

Open webpage inside my app after button is clicked

I have 5 buttons and i need to open different webpages after buttons is clicked. How to make it?
my java code for webview activity:
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebView extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url)
{
v.loadUrl(url);
return true;
}
}
And xml:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="lv.shit.test.Sakums" >
<webview android:id="#+id/manswebview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</webview>
</linearlayout>
What should I write on OnClick to open webpages in my webview?
You can load different pages on your webView object on the click.
as
webView.loadUrl("http://googlecom");
You can pas the url to the method loadUrl() under the webView object to preform the loading of different urls.
Call this method inside the onClick listener:
loadWebView(url);
public void loadWebView(String url){
/*
* Setting the options of my webView
*/
mWebView = (WebView)findViewById(R.id.manswebview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mWebView.loadUrl(url);
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
#Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
}
});
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
//when finish loading page
public void onPageFinished(WebView view, String url) {
}
});
//done loading now render the content
this.setContentView(mWebView);
}

Android WebView not loading URL

I want to load the URL in WebView
I have used the following Code:
webView = (WebView) findViewById(R.id.webview1);
webView.setWebViewClient(new HostsWebClient());
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setSupportZoom(false);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.loadUrl(URL);
But when I execute it, I'm not able to load the url. I am getting web page not available.
Could anyone help?
Did you added the internet permission in your manifest file ? if not add the following line.
<uses-permission android:name="android.permission.INTERNET"/>
hope this will help you.
EDIT
Use the below lines.
public class WebViewDemo extends Activity {
private WebView webView;
Activity activity ;
private ProgressDialog progDailog;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
progDailog = ProgressDialog.show(activity, "Loading","Please wait...", true);
progDailog.setCancelable(false);
webView = (WebView) findViewById(R.id.webview_compontent);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progDailog.show();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
progDailog.dismiss();
}
});
webView.loadUrl("http://www.teluguoneradio.com/rssHostDescr.php?hostId=147");
}
}
maybe SSL
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// ignore ssl error
if (handler != null){
handler.proceed();
} else {
super.onReceivedSslError(view, null, error);
}
}
Add Permission Internet permission in manifest.
as <uses-permission android:name="android.permission.INTERNET"/>
This code it working
public class WebActivity extends Activity {
WebView wv;
String url="http://www.teluguoneradio.com/rssHostDescr.php?hostId=147";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
wv=(WebView)findViewById(R.id.webUrl_WEB);
WebSettings webSettings = wv.getSettings();
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setPluginState(PluginState.ON);
wv.setWebViewClient(new myWebClient());
wv.loadUrl(url);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
Note : Make sure internet permission is given.
In android 9.0,
Webview or Imageloader can not load url or image because android 9 have network security issue which need to be enable by manifest file for all sub domain. so either you can add security config file.
Add #xml/network_security_config into your resources:
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.google.com</domain>
</domain-config>
</network-security-config>
Add this security config to your Manifest like this:
<application
android:networkSecurityConfig="#xml/network_security_config"
...>
</application>
if you want to allow all sub domain
<application
android:usesCleartextTraffic="true"
...>
</application>
Note: To solve the problem, don't use both of point 2 (android:networkSecurityConfig="#xml/network_security_config" and android:usesCleartextTraffic="true") choose one of them
For some web pages the key is to enable DOM storage:
webview.getSettings().setDomStorageEnabled(true);
First, check if you have internet permission in Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
You can then add following code in onCreate() or initialize() method-
final WebView webview = (WebView) rootView.findViewById(R.id.webview);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setBuiltInZoomControls(false);
webview.getSettings().setSupportZoom(false);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(URL);
And write a class to handle callbacks of webview -
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//your handling...
return super.shouldOverrideUrlLoading(view, url);
}
}
in same class, you can also use other important callbacks such as -
- onPageStarted()
- onPageFinished()
- onReceivedSslError()
Also, you can add "SwipeRefreshLayout" to enable swipe refresh and refresh the webview.
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
And refresh the webview when user swipes screen:
SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
webview.reload();
}
}, 3000);
}
});
Use the following things on your webview
webview.setWebChromeClient(new WebChromeClient());
then implement the required methods for WebChromeClient class.
Just as an alternative solution:
For me webView.getSettings().setUserAgentString("Android WebView") did the trick.
I already had implemented INTERNET permission and WebViewClient as well as WebChromeClient
The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView"/>
In my Case, Adding the below functions to WebViewClient fixed the error.
the functions are:onReceivedSslError and Depricated and new api versions of shouldOverrideUrlLoading
webView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.i(TAG, "loading: deprecation");
return true;
//return super.shouldOverrideUrlLoading(view, url);
}
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
Log.i(TAG, "loading: build.VERSION_CODES.N");
return true;
//return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
Log.i(TAG, "page started:"+url);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, final String url) {
Log.i(TAG, "page finished:"+url);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
handler.proceed();
}
});
Use this it should help.
var currentUrl = "google.com"
var partOfUrl = currentUrl.substring(0, currentUrl.length-2)
webView.setWebViewClient(object: WebViewClient() {
override fun onLoadResource(WebView view, String url) {
//call loadUrl() method here
// also check if url contains partOfUrl, if not load it differently.
if(url.contains(partOfUrl, true)) {
//it should work if you reach inside this if scope.
} else if(!(currentUrl.startWith("w", true))) {
webView.loadurl("www.$currentUrl")
} else if(!(currentUrl.startWith("h", true))) {
webView.loadurl("https://$currentUrl")
} else {
//...
}
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
// you can call again loadUrl from here too if there is any error.
}
// You should also override other override method for error such as
// onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point.
}

Android webview launches browser when calling loadurl

I created an Activity that has a title and a web view in a LinearLayout. In the onResume() method it calls webView.loadUrl(url). The problem is that the activity first shows the title with the rest of the screen blank, then the device browser is launched with the page for the URL. What I want to see is the page being shown in the WebView below the title. What could be the problem?
Edit:
Ok, did some further search and found this one:
Clicking URLs opens default browser
It points to the WebView tutorial here.
Just implement the web client and set it.
Answering my question based on the suggestions from Maudicus and Hit.
Check the WebView tutorial here.
Just implement the web client and set it before loadUrl. The simplest way is:
myWebView.setWebViewClient(new WebViewClient());
For more advanced processing for the web content, consider the ChromeClient.
Use this:
lWebView.setWebViewClient(new WebViewClient());
use like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dedline);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("https://google.com");
}
Make your Activity like this.
public class MainActivity extends Activity {
WebView browser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the WebView by name in the main.xml of step 2
browser=(WebView)findViewById(R.id.wvwMain);
// Enable javascript
browser.getSettings().setJavaScriptEnabled(true);
// Set WebView client
browser.setWebChromeClient(new WebChromeClient());
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
// Load the webpage
browser.loadUrl("http://google.com/");
}
}
I was facing the same problem and I found the solution
Android's official Documentation about WebView
Here is my onCreateView() method and here i used two methods to open the urls
Method 1 is opening url in Browser and
Method 2 is opening url in your desired WebView.
And I am using Method 2 for my Application and this is my code:
public class MainActivity extends Activity {
private WebView myWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
/* Method : 1
This following line is working fine BUT when we click the menu item then it opens the URL in BROWSER not in WebView */
//((WebView) rootView.findViewById(R.id.detail_area)).loadUrl(mItem.url);
// Method : 2
myWebView = (WebView) rootView.findViewById(R.id.detail_area); // get your WebView form your xml file
myWebView.setWebViewClient(new WebViewClient()); // set the WebViewClient
myWebView.loadUrl(mItem.url); // Load your desired url
}
return rootView;
} }
Try this code...
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (final WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(view.getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
If you see an empty page, enable JavaScript.
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);
Simply Answer you can use like this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
}
If you're using webChromeClient I'll suggest you to use webChromeClient and webViewClient together. because webChromeClient does not provides shouldOverrideUrlLoading. It is okay to use both.
webview.webViewClient = WebViewClient()
webview.webChromeClient = Callback()
private inner class Callback : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 0) {
progressBar.visibility = View.VISIBLE
} else if (newProgress == 100) {
progressBar.visibility = View.GONE
}
}
}
I just found out that it depends on the formatting of the URL:
https://example.com/example gets opened in the browser
https://example.com/example/ (with / at the end) gets opened in the webView
My code just uses
webview.loadUrl(url)
no need to set
webView.setWebViewClient(new WebViewClient())
at least in my case.
Maybe that's useful for some of you.
My problem ended up being that I needed to do a clearHistory before I could switch between sites without opening an external browser.
#Override
public void onPageFinished(WebView view, String url) {
webView_.clearHistory();
super.onPageFinished(webView_, url);
}

Categories

Resources