0
点赞
收藏
分享

微信扫一扫

安卓程序加载h5页面

少_游 2022-08-04 阅读 76


开发工具:Android Studio 2.2.0.0

 

一、 加载远程h5页面

1 新建一个Android工程MyWebViewDemo

 


2 在AndroidManifest.xml中添加互联网访问权限


<uses-permission android:name="android.permission.INTERNET"/>



添加完之后,AndroidManifest.xml的完整内容为:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yilinrun.mywebviewdemo">

<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



3 修改MainActivity.java中的onCreate方法


package com.example.yilinrun.mywebviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//实例化WebView对象
webview = new WebView(this);
//设置WebView属性,能够执行Javascript脚本
webview.getSettings().setJavaScriptEnabled(true);

try {
//设置打开的页面地址
webview.loadUrl("http://www.baidu.com");
} catch(Exception ex) {
ex.printStackTrace();
}

setContentView(webview);
}
}



4 运行结果

安卓程序加载h5页面_webview

 

二、 加载本地h5页面

可以在MyWebViewDemo中稍作改动即可。


1 右键app-->New-->Folder-->assets folder,生成assets文件夹,在assets文件夹里添加test.html文件,其内容为


<!doctype html>
<html>
<head>
</head>
<body>
Hello, I am a webview loading local H5.
</body>
</html>

安卓程序加载h5页面_webview_02




2 将MainActivity.java中的webview.loadUrl("http://www.baidu.com");


改为


webview.loadUrl("file:///android_asset/test.html");



3 运行结果

安卓程序加载h5页面_html_03

举报

相关推荐

0 条评论