どっこと備忘録群

アウトプットしないとインプットできない私が Androidアプリ開発をメインとした備忘録を載せています。

テキストをカスタマイズする(textStyle, textSize, textColor)

テキストを太字にする

android:textStyle="bold" を指定する。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

テキスト太字をプログラム上で設定する

TextView.setTypeface(Typeface, style) を使う。 styleにはTypeface.BOLDを指定する。

val textView = findViewById<TextView>(R.id.text_view)
textView.setTypeface(textView.typeface, Typeface.BOLD)

テキストを斜体にする

android:textStyle="italic" を指定する。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textStyle="italic"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

テキスト斜体をプログラム上で設定する

TextView.setTypeface(Typeface, style) を使う。 styleにはTypeface.ITALICを指定する。

val textView = findViewById<TextView>(R.id.text_view)
textView.setTypeface(textView.typeface, Typeface.ITALIC)

テキストを太字+斜体にする

android:textStyle="bold|italic"を指定する。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textStyle="bold|italic"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

太字+斜体プログラム上で設定する

TextView.setTypeface(Typeface, style)を使う。 styleにはTypeface.BOLD_ITALICを指定する。

val textView = findViewById<TextView>(R.id.text_view)
textView.setTypeface(textView.typeface, Typeface.BOLD_ITALIC)

テキストの大きさを変える

android:textSize を指定する。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textSize="24sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Androidでは端末の設定に文字サイズの項目があり、数段階で設定することができる。 この設定に合わせてフォントの大きさを変更してくれる単位がsp、設定に関わらず一律同じ大きさで表示する単位がdpとなる。 テキスト表示に対してはspを指定することが望ましい。

プログラム上で設定する

TextView.setTextSize(size) を使う

val textView = findViewById<TextView>(R.id.text_view)
textView.setTextSize(16f) // 16sp 指定

テキストの色を変える

android:textColor を指定する。

RGB による指定と、リソースIDによる指定がある。

RGBで指定する場合

RGB(Reg,Green,Blue)で指定する場合は以下。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textColor="#FF0000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

リソースIDで指定する場合

リソースIDで指定する場合は以下。

res/colors.xml にあらかじめ定義しておく。

<color name="text_color">#FF0000</color>

↑で定義したnametextColorで指定する。

<TextView
    android:id="@+id/text_view"
    android:text="サンプル"
    android:textColor="@color/text_color"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

テキストの色をプログラム上で設定する

TextView.setTextColor(color) を使う。

val textView = findViewById<TextView>(R.id.text_view)
textView.setTextColor(0xFF0000) // RGBで指定する

参考

最終更新: 2025.6.23