0

レイアウトにWebビューとボタン(Webビュー外)があります。ボタンをクリックしたときにjavascriptコードを実行する方法があるかどうかを知りたい(たとえば、OnClickイベントを使用して)

編集:

私はこのHTMLを持っています

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="PruebaAlert.js"></script>
    </head>
    <body>
       <!--Your content here-->

    </body>
</html>

PruebaAlert.jsに関数JSがあります

function myJSFunction(){
           alert('hello, i was hit by Android button');

}

public class MainActivity extends Activity {

int pulsado = 0;

//Controla que estamos usando el layout web_view_not_visible
boolean web_view_not_visible = true;
TextView text;
Button button;

WebView myWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view_not_visible);

    myWebView = (WebView)findViewById(R.id.webview);

    myWebView.loadUrl("file:///android_asset/StackOverflow.html");

    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);


    if(true){
        button = (Button)findViewById(R.id.button1);


        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("WebView Debug" , "Entre en onClick()");
                myWebView.loadUrl("javascript:myJSFunction()");
            }
        });

    }

}

}

ボタン(レイアウトの下部にあります)をクリックしましたが、アラートが表示されません。ChromeまたはFirefoxでHTMLを開くと、正常に機能します

何が起きましたか?


ありがとう!

4

2 に答える 2

2

html

<html>
    <head>
        <script type="text/javascript">
            function myJSFunction(){
               alert('hello, i was hit by Android button');
            }
        </script>
        //OR
        <script type="text/javascript" src="yourJSFile.js"></script>
    </head>
    <body>
       <!--Your content here-->
    </body>
</html>

yourJSFile.js

function myJSFunction(){
    alert('hello, i was hit by Android button');
}

onCreate

myWebView.loadUrl("yourHtml.html");

次に、ボタンがクリックされたときにjavascriptを呼び出すだけです。

myButton.setOnClickListener(new View.OnClickListener(){
   public void onClick(View v){
      myWebView.loadUrl("javascript:myJSFunction();");
   }
});
于 2013-03-27T08:07:14.353 に答える
1

このようにJavaScriptを呼び出すことができます

myWebView.loadUrl("javascript:test('arguments')");

コメントで聞いた2番目の質問について。

Where do i put my javascript file?

webviewがページをロードする方法は2つあります。1つはアプリケーションからhtmlページをロードし、もう1つは外部サイトを指す方法です。どちらの場合も、JSはHTMLが検索する場所に配置する必要があります。

于 2013-03-27T08:44:01.397 に答える