MainActivity.java
package pro.test.localweb;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// webView に関する試行錯誤
myWebView = (WebView) findViewById(R.id.localWeb);
myWebView.loadUrl("file:///android_asset/index.html"); // ローカルのhtmlファイルを指定
myWebView.setWebViewClient(new WebViewClient());
// WebView内のJavaScriptの実行を許可
myWebView.getSettings().setJavaScriptEnabled(true);
// WebChromeClientを設定する
// ※コレを設定しないとJSのalertは表示されない
myWebView.addJavascriptInterface(new JavaScript(this), "android");
}
}
app\src\main\assets\index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
test3
<div class="a"></div>
<br>
<button class="check" >Toastを表示</button>
</body>
<script>
$('.a').html("a")
$('.check').on('click',function(){
android.hogeMethod('ほげほげ')
//$('.a').html("testb")
});
</script>
</html>
pro/test/localweb/JavaScript.java
package pro.test.localweb;
import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
public class JavaScript {
private Context c;
private String IdString = "shop_admin1";
public JavaScript(Context c) {
this.c = c;
}
@JavascriptInterface
public void hogeMethod(String s) {
Toast toast = Toast.makeText(c, s, Toast.LENGTH_LONG);
toast.show();
}
@JavascriptInterface
public String GetLoginId(){
return IdString;
}
}