Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】TextViewの中で複数のテキストスタイルを組み合わせて表示する方法

この記事では、AndroidアプリのTextView内で複数のテキストスタイル(太字・斜体・文字サイズ・文字色など)を1つの文字列に混在させて表示する方法を解説します。

ポイントとなるのはHtml.fromHtml()メソッドです。HTMLタグを含む文字列をSpannedオブジェクトに変換してTextViewにセットすることで、文字列の一部だけを自由に装飾できます。

手順1:プロジェクトを新規作成する

Android Studioで「File」→「New Project」を選択し、必要事項を入力して新しいプロジェクトを作成します。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを記述します。サンプルでは3つのTextViewを画面中央付近に縦並びで配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_above="@id/textView2"
        android:layout_marginBottom="16dp"
        android:id="@+id/textView1"
        android:textSize="16dp"
        android:padding="4dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:padding="4dp"
        android:layout_centerInParent="true"/>
    <TextView
        android:layout_below="@id/textView2"
        android:layout_marginTop="16dp"
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:padding="4dp"/>
</RelativeLayout>

手順3:MainActivity.java を実装する

src/MainActivity.java に以下のコードを記述します。スタイル付き文字列の設定方法として、次の3つのパターンを確認できます。

  • textView1:Html.fromHtml()の結果を直接setText()に渡す
  • textView2:一度Spanned型の変数に格納してからsetText()に渡す
  • textView3:strings.xmlに定義したCDATA文字列を読み込んで表示する
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView1, textView2, textView3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1 = findViewById(R.id.textView1);
        textView2 = findViewById(R.id.textView2);
        // パターン1: fromHtmlの結果を直接セットする
        textView1.setText(Html.fromHtml("Multiple style inside android textView: bold text: "
            + "<b>bold text</b>, italic text: <i>italic text</i>, small font: <small>small "
            + "text</small>, "
            + "font color: <font color=\"blue\">Text Color</font>, "
            + "font color with bold text: <font color=\"green\"><b>Bold with font "
            + "color</b></font>"));
        // パターン2: Spanned型に格納してからセットする
        Spanned text = Html.fromHtml("Multiple style inside android textView: bold text: "
            + "<b>bold text</b>, "
            + "italic text: <i>italic text</i>, small font: <small>small text</small>, font "
            + "color: <font color=\"blue\">Text Color</font>, "
            + "font color with bold text: <font color=\"green\"><b>Bold with font "
            + "color</b></font>");
        textView2.setText(text);
        // パターン3: strings.xmlから読み込む
        textView3 = findViewById(R.id.textView3);
        textView3.setText(Html.fromHtml(getString(R.string.textStyle)));
    }
}

使用している主なHTMLタグとその効果は以下の通りです。

  • <b>〜</b>:太字
  • <i>〜</i>:斜体
  • <small>〜</small>:小さめのフォント
  • <font color="blue">〜</font>:文字色の変更(ネストして太字との併用も可能)

手順4:strings.xml にスタイル付き文字列を定義する

res/values/strings.xml を開き、以下のようにCDATAセクション内にHTMLタグを含む文字列を定義します。CDATAを使うことで、< や > などの特殊文字をエスケープせずにそのまま記述できるのが便利です。

<resources>
<string name="app_name">Sample</string>
    <string name="textStyle">
        <![CDATA[
            Multiple style inside android textView: bold text: <b>bold text</b>,
            italic text: <i>italic text</i>, small font: <small>small text</small>,
            font color: <font color="blue">Text Color</font>,
            font color with bold text: <font color="green"><b>Bold with font
            color</b></font>
        ]]>
    </string>
</resources>

手順5:AndroidManifest.xml を確認する

androidManifest.xml は以下の通りです。このサンプルでは特別な権限は不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

アプリを実行してみる

それではアプリを実行しましょう。実機のAndroid端末をPCに接続した状態で、プロジェクトのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デバイスを選択して起動すると、端末の画面に太字・斜体・小さめフォント・青字・緑色の太字が混在したテキストが表示されます。

【Android】TextViewの中で複数のテキストスタイルを組み合わせて表示する方法

補足:Html.fromHtml()の非推奨対応(API 24以降)

APIレベル24(Android 7.0)以降では、引数なしのHtml.fromHtml(String)は非推奨(deprecated)となっています。実運用ではフラグを指定するオーバーロード版を使用するか、AndroidXライブラリのHtmlCompatを利用するのがおすすめです。

// HtmlCompatを使う場合(androidx.coreが必要)
textView.setText(HtmlCompat.fromHtml(htmlText, HtmlCompat.FROM_HTML_MODE_LEGACY));

// SDKバージョンで分岐する場合
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY));
} else {
    textView.setText(Html.fromHtml(htmlText));
}
  1. 【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法

    概要 本記事では、AndroidアプリのTextViewに表示するテキストを両端揃え(ジャスティファイ)にする方法を、サンプルコードとともにわかりやすく解説します。 TextViewで両端揃えを実現するには、android:justificationMode=inter_wordを指定するだけです。この機能はAndroid 8.0(APIレベル26)以降で有効になるため、それ以前のOSバージョンでは無視される点に注意してください。 手順1:新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をす

  2. 【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法を徹底解説

    この記事では、AndroidアプリのTextViewでテキストを両端揃え(ジャスティファイ)表示する方法を、実際のサンプルコードをもとに段階的に解説します。RecyclerViewを使ったリスト表示の実装例もあわせて紹介するので、Androidアプリ開発の基礎固めとしても役立つ内容です。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な設定項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:res/layout/activity_main.xml