Kotlinを使ってAndroidのTextView内に複数のスタイルを作成する方法
このチュートリアルでは、Kotlinを使用してAndroidアプリのTextView内に太字・斜体・小さめフォント・文字色など、複数のスタイルを同時に適用する方法を解説します。
TextViewでHTMLタグによるリッチテキスト表現を実現するには、Html.fromHtml()メソッドを利用します。このメソッドは新しいAPIでは非推奨(Deprecated)となっているため、サンプルコードでは@Suppress("DEPRECATION")アノテーションを付けて警告を抑制しています。
ステップ1:新規プロジェクトの作成
Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な項目をすべて入力し、プロジェクトのセットアップを完了させてください。
ステップ2:レイアウトファイル(activity_main.xml)の編集
res/layout/activity_main.xmlに以下のコードを追加します。ここでは、スタイルを適用するためのTextViewを3つ縦に並べて配置しています。
<?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:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="150dp" android:padding="4dp" android:textAlignment="center" android:textSize="16sp" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_marginTop="70dp" android:padding="4dp" android:textAlignment="center" android:textSize="16sp" /> <TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView2" android:layout_marginTop="70dp" android:padding="4dp" android:textAlignment="center" android:textSize="16sp" /> </RelativeLayout>
ステップ3:MainActivity.ktの編集
src/MainActivity.ktに以下のコードを追加します。文字列の中に<b>(太字)、<i>(斜体)、<small>(小さめフォント)、<font color="...">(文字色)といったHTMLタグを埋め込むことで、1つのTextView内に複数のスタイルを混在させることができます。3つ目のTextViewでは、strings.xmlで定義した文字列リソースを読み込んで表示しています。
import android.os.Bundle
import android.text.Html
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
private lateinit var textView: TextView
private lateinit var textView2: TextView
lateinit var textView3: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
textView2 = findViewById(R.id.textView2)
textView3 = findViewById(R.id.textView3)
textView.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>"
)
val 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.text = text
textView3.text = Html.fromHtml(getString(R.string.textStyle))
}
}
ステップ4:strings.xmlの編集
res/values/strings.xmlを開き、以下のコードを追加します。CDATAセクション内にHTMLタグを含むテキストを記述することで、XMLパーサーにタグをそのまま文字列として扱わせることができます。
<resources> <string name="textStyle"> <![CDATA[ Multiple style inside android textView: bold text: <b>bold text</b>, italicText 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="com.example.q11"> <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スマートフォンがパソコンに接続されているものとします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの実行アイコン
をクリックします。ドロップダウンから接続したモバイルデバイスを選択すると、端末の画面に各スタイルが適用されたテキストが表示されます。

補足:Spannableによる代替手法
HTMLタグを使う方法以外にも、SpannableStringBuilderやSpannableStringを使用すれば、より柔軟にスタイルを制御できます。文字色にはForegroundColorSpan、太字にはStyleSpan(Typeface.BOLD)などを組み合わせるのが一般的です。実行時に動的にスタイルを切り替えたいケースでは、こちらの方法が便利なので、あわせて覚えておくとよいでしょう。
-
【Android開発】XMLスタイルでカスタムボタンを作成する方法をステップ解説
はじめに 本記事では、Androidアプリ開発においてXMLスタイル(Drawableリソース)を使用してカスタムボタンを作成する方法を、ステップごとにわかりやすく解説します。枠線のみのボタン、グラデーションボタン、角丸ボタンの3種類のデザインを、実際のコード例とともに紹介します。 手順1:新規プロジェクトの作成 まず、Android Studioを起動し、メニューから File → New Project を選択して新しいプロジェクトを作成します。必要事項をすべて入力し、プロジェクトのセットアップを完了させてください。 手順2:レイアウトファイルの編集 次に、res/layout/act
-
【Android】TextViewでテキストを両端揃え(ジャスティファイ)表示する方法
概要 本記事では、AndroidアプリのTextViewに表示するテキストを両端揃え(ジャスティファイ)にする方法を、サンプルコードとともにわかりやすく解説します。 TextViewで両端揃えを実現するには、android:justificationMode=inter_wordを指定するだけです。この機能はAndroid 8.0(APIレベル26)以降で有効になるため、それ以前のOSバージョンでは無視される点に注意してください。 手順1:新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をす