Android WebView 示例
Android WebView 用于在Android中顯示網(wǎng)頁(yè)。愛掏網(wǎng) - it200.com可以從同一應(yīng)用程序或URL加載網(wǎng)頁(yè)。愛掏網(wǎng) - it200.com它用于在Android活動(dòng)中顯示在線內(nèi)容。愛掏網(wǎng) - it200.com
Android WebView使用Webkit引擎來顯示網(wǎng)頁(yè)。愛掏網(wǎng) - it200.com
android.webkit.WebView是AbsoluteLayout類的子類。愛掏網(wǎng) - it200.com
Android WebView類的 loadUrl() 和 loadData() 方法用于加載和顯示網(wǎng)頁(yè)。愛掏網(wǎng) - it200.com
看看使用WebView顯示javatpoint.com網(wǎng)頁(yè)的簡(jiǎn)單代碼。愛掏網(wǎng) - it200.com
WebView mywebview = (WebView) findViewById(R.id.webView1);
mywebview.loadUrl("http://www.javatpoint.com/");
``````
讓我們來看一下簡(jiǎn)單的代碼, **顯示HTML網(wǎng)頁(yè)** 使用web view。愛掏網(wǎng) - it200.com在這種情況下,HTML文件必須位于資源目錄中。愛掏網(wǎng) - it200.com
```java
WebView mywebview = (WebView) findViewById(R.id.webView1);
mywebview.loadUrl("file:///android_asset/myresource.html");
``````
讓我們看看另一個(gè)用于顯示 **字符串的HTML代碼** 的代碼。愛掏網(wǎng) - it200.com
```java
String data = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";
mywebview.loadData(data, "text/html", "UTF-8");
``````
<h2> 完整的Android WebView示例 </h2> 讓我們看一個(gè)完整的Android WebView示例。愛掏網(wǎng) - it200.com </p><h4 id="h4"> activity_main.xml </h4><p>
```xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="example.javatpoint.com.webview.MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
將網(wǎng)頁(yè)(.html,.jsp)以本地應(yīng)用程序方式添加,需要將它們放置在assets文件夾中。愛掏網(wǎng) - it200.com創(chuàng)建assets文件夾的方法是:右鍵點(diǎn)擊app->New->Folder->Assets Folder->main,或者直接在主目錄內(nèi)創(chuàng)建一個(gè)assets目錄。愛掏網(wǎng) - it200.com
Activity類
package example.javatpoint.com.webview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mywebview = (WebView) findViewById(R.id.webView);
// mywebview.loadUrl("https://www.javatpoint.com/");
/*String data = "
# Hello, Javatpoint!
";
mywebview.loadData(data, "text/html", "UTF-8"); */
mywebview.loadUrl("file:///android_asset/myresource.html");
}
}
輸出:
如果您加載HTML頁(yè)面,我們來看一下輸出結(jié)果。愛掏網(wǎng) - it200.com
讓我們來看看加載javatpoint.com網(wǎng)頁(yè)后的輸出。愛掏網(wǎng) - it200.com