Thứ Bảy, 20 tháng 10, 2012

Android tutorial – display embedded HTML file in WebView

Working on Power Schedule, I wanted to make a short help file, with some formatting. It seems there were several ways of doing this, but I chose to include an embedded HTML file into my application. It seemed easier to just edit an HTML file in an editor.
So let’s get started…
  • first, embed an html file in the app resources. For this, create the “raw” subfolder in “res” folder and add your HTML formatted file:

  • use a WebView view in your layout file:
    1<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    2    android:id="@+id/webviewHelp android:layout_width="fill_parent"
    3    android:layout_height="fill_parent"/>   

  • use this code in your activity onCreate() method:
    1WebView webview = (WebView) findViewById(R.id.webviewHelp);
    2webview.loadData(readTextFromResource(R.raw.help), "text/html", "utf-8");
    where readTextFromResource is something like this:

    01private String readTextFromResource(int resourceID)
    02{
    03    InputStream raw = getResources().openRawResource(resourceID);
    04    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    05    int i;
    06    try
    07    {
    08        i = raw.read();
    09        while (i != -1)
    10        {
    11            stream.write(i);
    12            i = raw.read();
    13        }
    14        raw.close();
    15    }
    16    catch (IOException e)
    17    {
    18        e.printStackTrace();
    19    }
    20    return stream.toString();
    21}  

Không có nhận xét nào:

Đăng nhận xét

Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...