WebView with Java ScriptExample



MainActivity.java

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

JSCode js;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

WebView web = findViewById(R.id.web);
String file = "file:///android_asset/test.html";
web.getSettings().setJavaScriptEnabled(true);

js = new JSCode(this);

web.addJavascriptInterface(js, "call");
web.loadUrl(file);
}


public class JSCode {
Context mContext;
public JSCode(Context c) {
mContext = c;
}

@android.webkit.JavascriptInterface
public void show(String toast) {

AlertDialog.Builder a = new AlertDialog.Builder(mContext);
a.setTitle("Alert Message");
a.setMessage("Good Morning");
a.setCancelable(false);
a.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});

a.show();

}
}

}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"/>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

<LinearLayout>


test.html

<html>
<head>
<script type="text/javascript"
function get(){
call.show("Hello");
}
</script>

</head>
<body>
<form>

<div align="center" <input onclick="get()" type="button" value="Click me" /></div>

</form>
</body>
</html>



No comments: