Android 中動態改變 TextView 樣式(字體、顏色、大小等)有兩種主流做法:setTextAppearance(Context, resId) 套用 XML 定義的 Style,或直接呼叫 setter 方法逐項設定。前者可維護性佳,後者彈性高。
TextView textView = findViewById(R.id.myTextView);
textView.setOnClickListener(v -> {
// 套用粗體高亮樣式
textView.setTextAppearance(R.style.TextStyle_BoldHighlight);
// 或支援主題的版本 (API 23+)
// textView.setTextAppearance(context, R.style.TextStyle_BoldHighlight);
// 可選:同時變更背景
textView.setBackgroundColor(Color.parseColor("#000088"));
});
// 重置為正常
textView.setTextAppearance(R.style.TextStyle_Normal);
textView.setBackgroundColor(Color.parseColor("#000044"));
textView.setOnClickListener(v -> {
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTextColor(Color.WHITE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setBackgroundColor(Color.parseColor("#000088"));
});
SpannableString spannable = new SpannableString("重要:這是關鍵資訊");
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // "重要"
spannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new RelativeSizeSpan(1.2f), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
| API Level | 方法簽名 | 備註 |
|---|---|---|
| < 23 | setTextAppearance(int resId) | 已棄用 |
| 23+ | setTextAppearance(Context, int resId) | 支援主題屬性解析 |
// 相容寫法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextAppearance(context, R.style.TextStyle_BoldHighlight);
} else {
textView.setTextAppearance(R.style.TextStyle_BoldHighlight);
}
| 屬性 | 對應 Setter | 範例值 |
|---|---|---|
android:textStyle | setTypeface | normal, bold, italic, bold|italic |
android:textColor | setTextColor | #FF0000, @color/primary |
android:textSize | setTextSize | 16sp, 14dp |
android:typeface | setTypeface | normal, sans, serif, monospace |
android:fontFamily | setTypeface | @font/custom_font (API 16+) |
android:letterSpacing | setLetterSpacing | 0.1 (API 21+) |
android:shadowColor | setShadowLayer | #000000 |
setTextAppearance 切換。?attr/colorPrimary)請在 Style 中引用,支援深色模式自動切換。
onDraw、getView 等高頻呼叫中建立 Style/Spannable,預先建立快取。善用 XML Style 管理視覺一致性,搭配程式碼動態切換,即能實現優雅的執行時樣式變更。