首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TextView 執行時動態套用樣式:setTextAppearance 與 XML Style 實作

     編輯:程式設計綜合問答

Android 中動態改變 TextView 樣式(字體、顏色、大小等)有兩種主流做法:setTextAppearance(Context, resId) 套用 XML 定義的 Style,或直接呼叫 setter 方法逐項設定。前者可維護性佳,後者彈性高。

方案一:XML Style + setTextAppearance(推薦)

1. 定義 Style (res/values/styles.xml)



    
    
    

2. 程式碼套用


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"));

方案二:直接呼叫 Setter(彈性、無需 XML)


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 針對部分文字套用樣式


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方法簽名備註
< 23setTextAppearance(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);
}

Style 可設定屬性速查

屬性對應 Setter範例值
android:textStylesetTypefacenormal, bold, italic, bold|italic
android:textColorsetTextColor#FF0000, @color/primary
android:textSizesetTextSize16sp, 14dp
android:typefacesetTypefacenormal, sans, serif, monospace
android:fontFamilysetTypeface@font/custom_font (API 16+)
android:letterSpacingsetLetterSpacing0.1 (API 21+)
android:shadowColorsetShadowLayer#000000

最佳實踐建議

  • 通用樣式(標題、內文、按鈕文字)定義在 XML Style,程式碼用 setTextAppearance 切換。
  • 動態計算、單一處樣式變更用 Setter 或 SpannableString。
  • 3. 主題色彩(?attr/colorPrimary)請在 Style 中引用,支援深色模式自動切換。
  • 避免在 onDraw、getView 等高頻呼叫中建立 Style/Spannable,預先建立快取。

善用 XML Style 管理視覺一致性,搭配程式碼動態切換,即能實現優雅的執行時樣式變更。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved