Webview’s Html button click detection in Activity

This is how i implemented:

public class FirstActivity extends Activity {

WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mWebView = (WebView) findViewById(R.id.webView1);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    mWebView.loadUrl("file:///android_asset/html/File1.html");
}

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 nextScreen(String pro_cat_id) {

            startActivity(new Intent(mContext,
         MainActivity.class));
    }

And, in html file:

javascript: file3.js

function saveId(_id)
{
    localStorage.setItem("id", _id);
    Android.nextScreen(_id);
}

HTML:

<html>
    <head>
        <script type="text/javascript" src="https://stackoverflow.com/questions/20917235/arel/js/File3.js"></script>
    </head>
    <body>
        <button onClick="saveId('1');">1</button>
        <button onClick="saveId('2');">2</button>
    </body>
</html>

Leave a Comment