4

I'm developing an Android application using HTML design. This design contains a Form and Text Field and a submit Button.

HTML Code:

<form name="form1" onSubmit="return showInfo()" >
  First name:<input type="text" id="fname"  autofocus placeholder="First name"/>
  <input type="submit" value="submit" id="submitB"/>
</form>

Android Code:

WebView webView = (WebView)findViewById(R.id.WebView1);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/web/index.html");

The HTML design works well in the android UI, and this HTML file is connected to a separate Javascript file to handle the onsubmit event. For example, when the user presses on the submit button it calls a function in javascript file. All of this works great.

My question is: how I can reference this submit button in Java code? That is, I want this submit button in the HTML to be referenced in Java code when it is clicked on. I don't want to call the javascript function; I want, for example, to show a Toast message.

To illustrate :

<input type="submit" value="submit" id="submitB"/>
Button x = (button) findViewById(R.id.submitB) // I know this cant be happen but I want like this idea

I hope you got my Idea...

Phil
  • 35,852
  • 23
  • 123
  • 164
Abod R hawary
  • 58
  • 1
  • 4

1 Answers1

4

You need to use JavascriptInterface. To do this, first add your Java button and add it to the WebView:

Button submitB = (button) findViewById(R.id.submitB);
submitB.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(view.getContext(), "HTML Button Clicked!", Toast.LENGTH_SHORT).show();
    }
});
webView.addJavascriptInterface(submitB, "submitB");

Now you need to include the button statement in your HTML document, and specify the onClick attribute to perform the click on the Java button:

<button type="button" onclick="submitB.performClick()">Submit</button>

Now when you click the HTML button, it will show the toast message "HTML Button Clicked!"

Phil
  • 35,852
  • 23
  • 123
  • 164