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...

2
  • Is it required to use HTML and JavaScript? Why are you doing it like this instead of using simple android xml layouts? Commented Jan 10, 2014 at 19:52
  • I know it could be done by using simple xml layout,, but I'm doing that for a purpose Commented Jan 10, 2014 at 19:54

1 Answer 1

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

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

1 Comment

perfect and simple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.