A
Android-Torero
Neues Mitglied
- 0
Hallo zusammen,
beim Versuch, in meine App eine WebView für eine HTML-Seite einzubinden, stoße ich auf folgendes Problem:
Ich bekommen zwar die HTML-Seite angezeigt, der Aufruf einer JavaScript-Funktion, die in eine externe JS-Datei ausgelagert ist, will nicht funktionieren.
Folgenden Code habe ich versucht:
Activity (MainActivity.java):
Das WebAppInterface (WebAppInterface.java):
Die HTML-Datei (template.html):
JavaScript (funktionen.js):
Vielleicht hat jemand von euch eine Idee, warum das so nicht funktioniert bzw., was ich falsch mache. Bin auch für Alternativvorschläge offen, eine externe JS-Datei in eine WebView einzubinden
Gruß
Thore
PS: Noch eine Info vorweg, Die Html- und JS-Datei befinden sich im selben Verzeichnis "assets"
beim Versuch, in meine App eine WebView für eine HTML-Seite einzubinden, stoße ich auf folgendes Problem:
Ich bekommen zwar die HTML-Seite angezeigt, der Aufruf einer JavaScript-Funktion, die in eine externe JS-Datei ausgelagert ist, will nicht funktionieren.
Folgenden Code habe ich versucht:
Activity (MainActivity.java):
Code:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.wvJavaScript);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
String html = readHtml("template.html");
myWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
}
private String readHtml(String remoteUrl) {
String html = "";
AssetManager assetManager = getApplicationContext().getResources().getAssets();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(assetManager.open(remoteUrl)));
String str;
while((str = in.readLine()) != null) {
html += str;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if(in != null) {
try {
in.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
return html;
}
Code:
public class WebAppInterface {
Context context;
public WebAppInterface(Context c) {
this.context = c;
}
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
}
}
HTML:
<html>
<head>
<title>TEST</title>
<meta charset="utf-8">
<script type="text/javascript" src="file:///android_asset/funktionen.js"></script>
</head>
<body>
<h1>My Web View</h1>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</body>
</html>
Code:
<script type="text/javascript" language="JavaScript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
Gruß
Thore
PS: Noch eine Info vorweg, Die Html- und JS-Datei befinden sich im selben Verzeichnis "assets"
Zuletzt bearbeitet: