How do I open html via asset? I'm trying to create a text editor for my application.
How do I open html via asset? I'm trying to create a text editor for my application.
There are two very simple ways. First of all, we need to create the WebView element in XML , for example:
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In the Java file, we need to instantiate this element:
WebView navegador = findViewById(R.id.webView);
Once you've done this,
1. Just create a file in the src/main/assets
folder, for example codigo.html
and within this file, just add your HTML tag. To load the file into WebView using the loadUrl
method, for example:
navegador.loadUrl( "file:///android_asset/codigo.html" );
2. Another way is to use the loadData
method of WebView , for this we should use getAssets().open("codigo.html");
, for example:
try {
WebView navegador = findViewById(R.id.webView);
InputStreamReader inputStream = new InputStreamReader(getAssets().open("codigo.html"));
StringBuilder codigo = new StringBuilder();
char[] b = new char[1024];
while (inputStream.read(b) != -1) {
codigo.append(b);
}
navegador.loadData(codigo.toString(), "text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}