Skip to content Skip to sidebar Skip to footer

How To Detect Div Tag From Html File?

I am loading html page in web view. In html there is a button; on click of that, I have to start a new activity. I have displayed html file but how to detect the click of button ?

Solution 1:

use this :

Html:

 <div id="button" onclick="Helper.methodeone()">
 <ul>
     <li><a title="Forming a Habit" href="Forming_Habit.html">
         More
         <span class="arrows">
             &nbsp;&#187;
         </span>
     </a></li>
 </ul>

on java :

    webView.setWebViewClient(new MyWebViewClient());
    WebSettings webSetting = webView.getSettings();
    webSetting.setJavaScriptEnabled(true);
    webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
    //webSetting.setBuiltInZoomControls(true);
    webSetting.setAllowContentAccess(true);
    web.addJavascriptInterface(new Samlplejavaconect(), "Helper");//NEW LINE
    webSetting.setDefaultTextEncodingName("utf-8");
    webView.loadUrl("file:///android_asset/"+htmlFile);

And in below class you can manage activity :

public class Samlplejavaconect {
    public void methodeone() {
        Toast.makeText(this, "Hi", Toast.LENGTH_LONG).show();//FOR EXAMPLE
    }
}

Solution 2:

Try this

MainActivity.java

public class MainActivity extends Activity {
WebView webView;
JavaScriptInterface jsInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webView1);
    WebSettings webSettings = webView.getSettings();
    // enable JavaScript
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient() {
    });
    jsInterface = new JavaScriptInterface(MainActivity.this, webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(jsInterface, "AndroidFunction");
    webView.loadUrl("file:///android_asset/book.html");
}

public class JavaScriptInterface {
    private Activity activity;
    WebView wb;

    public JavaScriptInterface(Activity activiy, WebView wb) {
        this.activity = activiy;
        this.wb = wb;
    }
    @JavascriptInterface
    public void activity() {
        try {
            Class activity = Class.forName("com.example.classname");
            Intent myIntent = new Intent(getApplicationContext(), activity);
            startActivity(myIntent);
            finish();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

}

book.html

<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="startactivity()">Click Me!</button>
<script>
function startactivity() {
   AndroidFunction.activity();
}
</script>
</body>
</html>

Post a Comment for "How To Detect Div Tag From Html File?"