0

This question may sound basic for many of you. But please take a look at my actual problem. I am setting content of my WebView dynamically in my android application. And I am able to set text in it without having any problem but my problem is I need to add some button dynamically into my WebView as below

for (Address address : (List<Address>) childDataList.get(3)) {

    if (!address.getName().equalsIgnoreCase("")) {
        text.append("<b>").append(address.getName()).append("</b>");
    }


    /*  dynamic button in html */
   //text.append("<br>").append("<a href=\"http://www.google.com\" target=\"_parent\"><button>Navigation </button></a>");   // this is working
   text.append("<br>").append("<button type=\"button\" onclick=\"ok.performClick();\">Navigation</button>");    // not able to make it work
   text.append("<br><br>");

}

And I am calling this method using the below code:

WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new Object()
{
  public void performClick()
  {
    //Print Toast
  }
}, "ok");

However performClick() method is not calling on button click, while it is working perfectly incase of direct url. So if you have any suggestion or link please provide for me.

I followed android html button onclick event and webviews html button click detection in activityjava code and detect click on html button through javascript in android webview link, but I am unable get my requirement done.

And I am setting my webview text programmatically Android code not in Javascript. So please take a look at my question before marking it as duplicate or if I missing something then guide me.

0

1 Answer 1

0

You need to annotate performClick with @JavascriptInterface (doc) in your Java code:

wv.addJavascriptInterface(new Object()
{
    @JavascriptInterface
    public void performClick()
    {
        //Print Toast
    }
}, "ok");

Also, make sure that you are calling addJavascriptInterface before loading your page.

Sign up to request clarification or add additional context in comments.

2 Comments

I have a doubt here does the name performClick has to match both in Java as well as javascript if i change perform click to any other text will the click still work ?
Yes, your calls in JavaScript must use the name of the Java function. If you rename it, you will have to change your JavaScript code accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.