1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.example.webviewdemo;
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.JavascriptInterface; import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/myfile.html");
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android"); }
public class WebAppInterface { Context mContext;
WebAppInterface(Context c) { mContext = c; }
@JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } }
|