把網頁放到安卓app中

創建空app 展示網頁

首先配置權限

在 app/src/main/AndroidManifest.xml 添加網絡權限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.countrymanage">
    
	<?- 網絡權限-?>
    <uses-permission android:name="android.permission.INTERNET" />
    省略。。。

啓用javascript

        val myWebView = WebView(this)
        myWebView.settings.javaScriptEnabled = true
        setContentView(myWebView)

方法一 直接代碼修改

    //官方示例中的 activityContext 就是上下文 this
    //val myWebView = WebView(activityContext)
        val myWebView = WebView(this)
        setContentView(myWebView)
        myWebView.loadUrl("http://www.baidu.com")
    

我的 應用
在這裏插入圖片描述

方法二 手動修改xml 較爲麻煩

替換xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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


</androidx.constraintlayout.widget.ConstraintLayout>

加載頁面

 val myWebView: WebView = findViewById(R.id.webview)
    myWebView.loadUrl("http://www.example.com")
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章