如何在Android的TextView中顯示HTML?
在某些情況下,我們需要在Android中將HTML顯示為文字。以下是在Android的TextView中顯示HTML的簡單解決方案。
步驟 1 - 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟 2 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:id = "@+id/rootview" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" tools:context = ".MainActivity"> <TextView android:id = "@+id/htmlToTextView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout>
步驟 3 - 將以下程式碼新增到src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v4.text.HtmlCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String htmlText = "<h2>What is Android?</h2>
" + "<p>Android is an open source and Linux-based <b>Operating System</b> for mobile devices such as smartphones and tablet computers.
Android was developed by the <i>Open Handset Alliance</i>, led by Google, and other companies.</p>
" + "<p>Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.</p>
" + "<p>The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 whereas the first commercial version, Android 1.0, was released in September 2008.</p>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlToTextView = findViewById(R.id.htmlToTextView);
htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
}
}在上面的示例中,我們將HTML標籤儲存在名為htmlText的字串中,並如下所示將字串新增到TextView中。
htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
在上面的程式碼中,我們從fromHtml()獲取HTML資料,並使用setText()將其新增到TextView中。0是一個標誌,您可以根據專案資源分配標誌。
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您專案中的一個活動檔案,然後單擊執行
工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

在上面的示例中,它顯示HTML標籤作為字串。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP