Open HTML via Asset

Asked

Viewed 478 times

0

How do I open html via Asset? I’m making my text editor application, I really need to learn how to open html via Asset.

1 answer

1

There are two very simple ways. First of all, we need to create the element Webview in the XML, for example:

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

In the archive Java, we need to instantiate this element:

WebView navegador = findViewById(R.id.webView);

Once this is done, let’s look at ways to load a file from the folder Assets:

1. Just create a file in the folder src/main/assets, for example codigo.html and inside this file, just add your code HTML. To upload the file to Webview through the method loadUrl, for example:

navegador.loadUrl( "file:///android_asset/codigo.html" );

2. Another way is to use the method loadData of Webview, for this we must 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.