テキストをカスタマイズする(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>
↑で定義したname
を textColor
で指定する。
<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