20

I am implementing a webview. I want two buttons on the top of the web page.

I have one vertical linear layout, inside of which is one horizontal layout with two buttons, and one webview outside of the horizontal layout.

I am simply loading the Google URL in Java code.

Every time I run the application, it opens a new browser on top of the application and the buttons get hidden. It's not showing the buttons above the webview. Please help and tell me how can I load a URL in the webview without opening another browser, or how I can prevent it by opening a native browser, so that the page is loaded in the webview itself and not a new browser.

Thanks all

jscs
  • 63,694
  • 13
  • 151
  • 195
Vishal Arora
  • 543
  • 3
  • 8
  • 19

9 Answers9

50

Ya. You must implement WebViewClient class and Override shouldOverrideURLLoading() method in this class.

Why ? Because webview just open your "exactly link", if that link redirect other links, android will open default browser for this action.

In your example, as you know, when you connecting to google.com google will redirects to google at your country. Example, if you are in China, google will go to google.com.cn, if in Vietnam, will be google.com.vn.

Here is my simple example: (you can imagine this is an new browser, :laugh)

First is layout xml file:

<?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" >

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

        <EditText 
            android:id="@+id/url"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:hint="Input URL"/>

        <Button 
            android:id="@+id/run"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="0"
            android:text="GO"/>

    </LinearLayout>

    <WebView 
        android:id="@+id/webview"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"/>

</LinearLayout>

Here is code of main activity:

package com.basic;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class WebViewExample extends Activity{ 

    WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        webView = (WebView) findViewById(R.id.webview);

        Button button = (Button) findViewById (R.id.run);
        button.setOnClickListener(new OnClickListener() {           
            @Override
            public void onClick(View v) {
                gotoPage();             
            }
        });

    }

    private void gotoPage(){

        EditText text = (EditText) findViewById(R.id.url);
        String url = text.getText().toString();

        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);

        webView.setWebViewClient(new Callback());  //HERE IS THE MAIN CHANGE
        webView.loadUrl(url);

    }

    private class Callback extends WebViewClient{  //HERE IS THE MAIN CHANGE. 

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

    }

}

Hope this help you :)

hqt
  • 29,632
  • 51
  • 171
  • 250
  • I had to implement the WebViewClient because the webview.loadUrl() was opening the browser directly. But ONLY ON Xoom with ICS (4.0.3) Works perfectly fine with my Acer Iconia 7' under Honeycomb (3.2.1). Have you ever heard anything like that ? – Patrice Cote May 31 '12 at 00:46
21

Adding the following code before loadUrl() will solve this problem,

wv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
          view.loadUrl(url);
          return true;
           }}); 

The shouldOverrideUrlLoading() from WebViewClient does this job. Here goes the Android doc for shouldOverrideUrlLoading,

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url...

http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading%28android.webkit.WebView,%20java.lang.String%29

Sathesh
  • 6,323
  • 6
  • 36
  • 48
  • 1
    this is totally wrong; it adds each redirected url to the history stack. per the other answers, your web view client should simply return `false`. it should not call `loadUrl` and return `true`. – j__m Aug 16 '16 at 12:16
10

My XML implementation:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent">

<WebView
    android:background="@android:color/transparent"
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></WebView>
</RelativeLayout>

My Java implementation:

WebView webView;
public final String GlobalUrl = "http://slashdot.org/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_application_activity);

    webView = (WebView) findViewById(R.id.webView);
    loadWebViewLoad(webView);
}

private void loadWebViewLoad(WebView webview) {
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webview.getSettings().setSupportMultipleWindows(true);
    webview.setWebViewClient(new WebViewClient());
    webview.setWebChromeClient(new WebChromeClient());
    webview.loadUrl(GlobalUrl);
}

And final result is:

Example image

d.danailov
  • 9,594
  • 4
  • 51
  • 36
4

I had the exact same problem and fortunately after browsing the web for about an hour I mixed some of the things I found and it worked.

this is the code:

WebView webView;
webView = ((WebView) rootView.findViewById(R.id.detail_area));
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(mItem.link);

where "detail_area" was my webview, rootView was my selected item inside a "Master/Detail Flow", link was the URL I wanted to open.

Idan Damri
  • 196
  • 10
4

The layout should something similar to this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:layout_height="fill_parent"
                 android:layout_width="fill_parent"
                 android:orientation="vertical">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <Button android:id="@+id/button1"
                android:layout_width="0dip"
                android:layout_height="wrap_content"                
                android:layout_gravity="top"
                android:layout_weight="1"/>
            <Button android:id="@+id/button2"
                android:layout_width="0dip"
                android:layout_height="wrap_content"                
                android:layout_gravity="top"
                android:layout_weight="1" />
        </LinearLayout>
        <WebView 
            android:id="@+id/webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
</LinearLayout>

And you can also refer to the Need help changing from stock android browser to webview to see if you are launching the url correctly.

Community
  • 1
  • 1
Rajath
  • 11,787
  • 7
  • 48
  • 62
  • 1
    thanks for ur reply..but my problem remains the same. as soon as i load url to the webview, it takes full screen as if a new activity or browser being opened over the application. on clicking of back button, it takes me to the application where i can see 2 buttons and webview that is blank and white. – Vishal Arora Apr 06 '11 at 09:39
  • can you share the code in your webview's parent activity... just the relevant parts. Also, the code which launches the url. – Rajath Apr 06 '11 at 09:45
  • xml is same as answered. my java code is : public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); browser = (WebView)findViewById(R.id.webView); browser.loadUrl("http://www.google.com"); browser.getSettings().setJavaScriptEnabled(true); showPrevious = (Button)findViewById(R.id.showPrevious); showNext = (Button)findViewById(R.id.showNext); }); } – Vishal Arora Apr 06 '11 at 10:16
  • 7
    have you added the following - `browser.setWebViewClient(new WebViewClientSubClass());` before `browser.loadUrl("google.com");`? – Rajath Apr 06 '11 at 10:18
  • added now..it works as needed..thanks a lot..but i dint get why we do that and how does it affect the layout..can u please explain?? and thanks again.. – Vishal Arora Apr 06 '11 at 10:28
  • 2
    My guess is that (if the page IS loading), since the WebView does not have a client associated with it, the system might be requesting the stock browser to launch the url. – Rajath Apr 06 '11 at 10:35
  • @rajath this works for me. but How to save a back track of the web pages. when ever I press the back button it finish my app. I want to go back to home page first and then if a user further press the back button then it must quit my app. How to do this? please help – Qadir Hussain Nov 07 '13 at 12:33
  • 1
    @QadirHussain, register an onKeyListener() with the WebView, and capture the button. Based on the current state of the pages in your WebView, you can do as you please. – Rajath Nov 07 '13 at 12:48
2

I tried this. its working for me. it does not open new window. it will open webview page only. its hiding for new browser asking window open..

private WebView webView;
String strUrl="url" ;

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(strUrl);
webView.setWebViewClient(new WebViewClient());
harikrishnan
  • 1,985
  • 4
  • 32
  • 63
1

Add the below line in your xml file which having webview

tools:context=".MyActivity" (name of your activity)

Dhasneem
  • 4,037
  • 4
  • 33
  • 47
0

This might be a late post but it might help other developers...

You need to set setWebViewClient on webview before loading the URL on it like below,

webview.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return false;
    }
});

Some background of the above code, Documentation states in literals words like below about the shouldOverrideUrlLoading method.

 * @param view The WebView that is initiating the callback.
 * @param request Object containing the details of the request.
 * @return {@code true} if the host application wants to leave the current WebView
 *         and handle the url itself, otherwise return {@code false}.
 */
@Override
@SuppressWarnings("deprecation") // for invoking the old shouldOverrideUrlLoading.
@RequiresApi(21)
public boolean shouldOverrideUrlLoading(@NonNull WebView view,
        @NonNull WebResourceRequest request) {
    if (Build.VERSION.SDK_INT < 21) return false;
    return shouldOverrideUrlLoading(view, request.getUrl().toString());
}

If you see the documentation above for returning the value, it says,

@return {@code true} if the host application wants to leave the current WebView
  *and handle the url itself, otherwise return {@code false}.

So it simply says, If you return true from shouldOverrideUrlLoading method, it'll ask the default browser of your device to handle the request of opening the URL and if you return false, then your URL will be loaded through webview only.

Now you can load your URL in webview either after this setWebViewClient call or you can also load your URL inside shouldOverrideUrlLoading method before returning the value.

Abhishek Kumar
  • 4,532
  • 5
  • 31
  • 53
-1

this code work for me thanks...

    WebView wbView = (WebView) findViewById(R.id.webView);

    wbView.getSettings().setJavaScriptEnabled(true);
    wbView.setWebViewClient(new WebViewClient());
    wbView.loadUrl("http://ppid.polinela.ac.id");
  • 2
    Including an explanation of your code would make this answer more useful. Further, this code is nearly identical to the example in at least one of the existing answers, so this does not seem to contribute any new information to the discussion. – faintsignal Sep 09 '18 at 19:34