0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript から javaを呼び出せた 最初のソース

Last updated at Posted at 2020-05-08

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;
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?