簡體   English   中英

如何在 TextView 中顯示格式化文本?

[英]How can I display formatted text in a TextView?

如何在 TextView 中顯示格式化文本?

簡單地將格式化文本復制並粘貼到字符串資源文件中也不起作用。

<string name="some_text">Some Formatted text copied from browser</string>

爪哇:

TextView textView = (TextView) findViewById(R.id.some);
textView.setText(getString(R.string.some_text));

但它顯示為普通文本。 要求是顯示彩色或粗體文本等。

如果您想設置文本樣式,您有幾個選擇。


最簡單的方法是使用 HTML 標簽。 不過你必須用CDATA包裝它。

例如,您可以創建您的字符串:

<string name="some_text"><![CDATA[Create stickers for <b>Gboard</b>...]]></string>

然后顯示它,你可以這樣做。

Spanned sp = Html.fromHtml( getString(R.string.some_text));
tv.setText(sp);

現在,更健壯的方法是實際使用 Android 的樣式。

您需要創建多個TextView ,每個都有自己的 Style,這將允許您對文本的確切外觀進行大量控制。

例如,這是一個您可以執行類似操作的布局。

<?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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Creating a Title for your layout. -->
    <TextView
        style="@style/TextAppearance.AppCompat.Title" <!-- Title Style -->
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Create stickers for Gboard on Google Play"
         />
    <!-- Creating a subheader for your layout. -->
    <TextView
        style="@style/TextAppearance.AppCompat.Caption" <!-- Caption Style -->
        android:id="@+id/subheader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="01 September 2017"
         />

</LinearLayout>

對於您擁有的每種不同格式,您需要創建一個新的TextView ,並應用正確的樣式。

我建議堅持使用@style/TextAppearance.AppCompat...下的任何內容,因為這將為您提供文本大小/重量的非常好的起點。

您可以使用TitleCaptionBody2Body1等內容。


然后,當您對樣式有了更多經驗時,您就可以開始創建自己的樣式了。

例如,假設我希望我的所有 Titles 都是RED 您首先在styles.xml創建一個樣式

<style name="myTitleStyle" parent="TextAppearance.AppCompat.Title">
    <item name="android:textColor">@color/red</item>
</style>

然后你就可以像以前的樣式一樣使用它了。

<!-- Creating a Title for your layout. -->
        <TextView
            style="@style/myTitleStyle" <!-- myTitleStyle Style -->
            android:id="@+id/header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Create stickers for Gboard on Google Play"
             />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM