首先我們先制定一個test.html,並放到assets\資料夾下。
assets/test.html
<!DOCTYPE HTML> <html> <body> <p>WebView</p> <b>This is a test page</b> <p>Thanks</p> </body> </html>
資料夾存放路徑
●主程式中,我們會利用下列的路徑格式讀取assets裡的html
file:///android_asset/檔名下面程式會在程式啟動後,使用WebView顯示assets目錄下的test.html
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
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.loadUrl("file:///android_asset/test.html");
 }
}
這裡補充一點,假如您需要多國的版本,如test_eng.html或test_tw.html則可以先在strings.xml裡做相對應的字串
<string name="url_to_load">file:///android_asset/test_eng.html</string>
然後在程式裡利用webView.loadUrl(getString(R.string.url_to_load));讀出來。
●在layout裡加入一個webView就完成啦
activity_main.xml
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
●最後在AndroidManifest.xml加入INTERNET存取的權限
<uses-permission android:name="android.permission.INTERNET" />
●結果
 
沒有留言:
張貼留言