How to capture html button click to call an android java method?

1

Dear liking in greeting them, I am working in Android Studio creating an environment with WebView, in this there is a button that when pressing it should call a function created in java. Is it possible to approach this dynamic linking with addJavascriptInterface () ?. I would appreciate some guidance. Thank you very much

    
asked by Cristian Bossardt 06.08.2018 в 21:06
source

1 answer

1

first you need to create an interface class

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Then add the interface to the WebView with the following code:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

And at the end in your HTML code do the following:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

You can find more information at: link

    
answered by 07.08.2018 в 05:34