2013-05-08 71 views
0

我有使用android webview的應用程序。我試圖從Java調用JavaScript。我在下面預計顯示hello world,但是webview變爲空白。從Java調用Javascript - Android

webView = (WebView) findViewById(R.id.webView); 
webView.getSettings().setJavaScriptEnabled(true); 

webView.loadUrl("javascript:document.write('hello world')"); 

我的代碼是否正確或錯過了什麼?

使用document.write顯示僅用於調用JS函數的測試目的。

回答

2

先改變我試過這個字符串爲 「世界你好」,從 「你好」 :-)

,它正在

活動

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     WebView webView = (WebView) findViewById(R.id.webView1); 
     webView.getSettings().setJavaScriptEnabled(true); 

     webView.loadUrl("javascript:document.write('hello world')"); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 


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

</RelativeLayout> 
+0

嗨,我已經試過你的答案,但沒有成功..你能幫我解決我的問題嗎? http://stackoverflow.com/questions/42633793/call-javascript-function-from-android-activity-class – 2017-03-06 20:52:25

0
Try this way 

wview.loadUrl("file:///android_asset/index.html"); 

    **index.html** 
copy index.html in assests folder 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <title>Insert title here</title> 
    </head> 
    <body> 
    <h1>Hello World</h1> 
    </body> 
    </html> 
+0

我用'document.write'來寫'hello world'只用於測試目的。要求是調用JS函數,而不是隻顯示'hello world'。 – 2013-05-08 08:15:15

+0

笏你的要求可以呃 – User 2013-05-08 08:26:07