Muhammed Refaat
Muhammed Refaat

Reputation: 9103

assign onClickListener for WebView html views

I have a WebView contains some html code, this html code is a code that displays five buttons created through it, I want to listen to the onClick or onTouch action of these buttons so that when the user clicks on it some action happens, all I want to know is how to assign onClick for these views which is created by html, and for sure the onClick process can be added to buttons through the html code itself so it will OK also if there is a way to assign an onClick regarding to html code.

Upvotes: 0

Views: 1004

Answers (2)

Ganesh AB
Ganesh AB

Reputation: 4698

You need to write JavaScript for HTML button click listeners.

<button type="button" id="exit" onclick="exitButtonClick();">Exit</button>

<script language="javascript">

   function exitButtonClick()
   {
      // Do Something
   }

</script>

If you want to call native java code from HTML's buttons then you need to add JavaScriptInterface to your WebView. For details please check below link

http://developer.android.com/guide/webapps/webview.html

Upvotes: 1

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

You can't add listener for html's buttons in android code. Instead, you can use Javascript Interface with Webview.

public final class MyJSInterface
{
    public void button1function(){
        //do something
    }
}

Write all functions in this Interface.

Add that JSInterface to your webview.

myWebView.addJavascriptInterface(new MyJSInterface(), "MyJSInterface");  //name you want that will be used in javascript file.

Now in your html's javascript, you can call these functions using JavaScriptInterface name:

function method1() {
    MyJSInterface.button1function();
}

Hope this helps.

Upvotes: 0

Related Questions