編輯:關於 Android 程式設計
想讓 TextView 裡的某幾個字顯示出不同的顏色或背景?借助 SpannableStringBuilder 就能輕鬆實現,效果類似於在 HTML 中為指定文字標記樣式。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str = "這是設置TextView部分文字背景顏色和前景顏色的demo!";
int bstart = str.indexOf("背景");
int bend = bstart + "背景".length();
int fstart = str.indexOf("前景");
int fend = fstart + "前景".length();
SpannableStringBuilder style = new SpannableStringBuilder(str);
style.setSpan(new BackgroundColorSpan(Color.RED), bstart, bend, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.RED), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
TextView tvColor = (TextView) findViewById(R.id.tv_color);
tvColor.setText(style);
}
}
把這套邏輯封裝成一個方法,項目中調用起來就更方便了:
// textview 設置部分顏色
public SpannableStringBuilder setPartColorText(String str) {
// 使用 SpannableStringBuilder 類
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(str);
// 確定部分顏色的位置
int start = str.indexOf(content);
int end = start + content.length();
// 確定顏色為紅色
ForegroundColorSpan mForeColor = new ForegroundColorSpan(Color.RED);
// setSpan
spannableStringBuilder.setSpan(mForeColor, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableStringBuilder;
}
除了前景與背景着色,SpannableString 家族還提供了豐富的 Span 類型,可以實現更多樣的文本效果:
AbsoluteSizeSpan(int size) —— 設置字體大小,參數為絕對數值,相當於 Word 中直接指定字號。
RelativeSizeSpan(float proportion) —— 設置字體大小,參數為相對於默認字體大小的倍數。若默認字體為 x,設置後即為 x * proportion,使用起來更靈活:proportion > 1 放大,proportion < 1 縮小。
ScaleXSpan(float proportion) —— 橫向縮放字體,默認為 1,設置後為原值乘以 proportion,大於 1 放大,小於 1 縮小。
BackgroundColorSpan(int color) —— 背景着色,參數為顏色數值,可直接使用 android.graphics.Color 中定義的常量,或用 Color.rgb(int, int, int)。
ForegroundColorSpan(int color) —— 前景着色,也就是文字本身的顏色,參數用法與背景着色一致。
TypefaceSpan(String family) —— 設置字體,參數為字體名稱,如 "sans"、"sans-serif" 等。
StyleSpan(Typeface style) —— 設置字體風格,如粗體、斜體,參數為 android.graphics.Typeface 中定義的常量,如 Typeface.BOLD、Typeface.ITALIC 等。
StrikethroughSpan —— 設置後會有一條線從文字中間穿過,呈現刪除線效果。

自訂 Android View 實作:打造可重複使用的 MenuItemView 設定列
在設定頁或選單頁中,常會出現大量重複的列表樣式。若每次都重寫版面,維護成本很高。本文介紹如何自訂 MenuItemView,將常見的設定列封裝成可重複使用的 View。
仿 iPhone 風格對話框(附範例、jar 包與源碼)
效果圖: 這個對話框完全繼承並仿照 AlertDialog,只是實作了自定義外觀。由於 iPhone 的對話框大多沒有圖標,因此這裡沒有實作 setIcon。 附件
Dalvik 學習筆記:Zygote 啟動流程源碼逐段解析
上圖大致說明了 Zygote 的啟動過程。下面從 app_process.main 開始,逐段解析其中的關鍵函式。 一、app_process 的 main 函式 i
更省事也更完整的 Material Design 狀態列方案彙整
從實際需求出發,用盡可能簡短的方式實行了七種常見的 MD 狀態列型態。核心關鍵其實只有一個:fitsSystemWindows 該加在哪一層。 零、使用前提 Theme