@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.tvContent); final SpannableStringBuilder style = new SpannableStringBuilder(); //設置文字 style.append("註冊即爲贊成《某某某協議》"); //設置部分文字點擊事件 ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, "觸發點擊事件!", Toast.LENGTH_SHORT).show(); } }; style.setSpan(clickableSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(style); //設置部分文字顏色 ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF")); style.setSpan(foregroundColorSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //配置給TextView tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(style); }
簡單介紹一下SpannableStringBuilder,這個類實際上就是對你的TextView中的文字進行簡單的配置,配置好你想要的屬性後,直接調用下面代碼便可:java
//設置光標如何移動計量的方法
textView.setMovementMethod(LinkMovementMethod.getInstance());
//配置給TextView
textView.setText(style)
如何進行各個屬性的配置呢?咱們以字體設置顏色爲例:app
//設置部分文字顏色ide
//建立字體顏色的Span,並初始化字體顏色屬性
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
//咱們設置第7~13箇中間的字符爲藍色
style.setSpan(foregroundColorSpan, 7, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);字體
SpannableStringBuilder和SpannableString主要經過使用setSpan(Object what, int start, int end, int flags)改變文本樣式。ui
setSpan()方法對應的參數以下:this
start: 指定Span的開始位置
end: 指定Span的結束位置,並不包括這個位置。
flags:取值有以下四個
Spannable. SPAN_INCLUSIVE_EXCLUSIVE:前面包括,後面不包括,即在文本前插入新的文本會應用該樣式,而在文本後插入新文本不會應用該樣式
Spannable. SPAN_INCLUSIVE_INCLUSIVE:前面包括,後面包括,即在文本前插入新的文本會應用該樣式,而在文本後插入新文本也會應用該樣式
Spannable. SPAN_EXCLUSIVE_EXCLUSIVE:前面不包括,後面不包括
Spannable. SPAN_EXCLUSIVE_INCLUSIVE:前面不包括,後面包括
詳細實現方式都已經在【Android】強大的SpannableStringBuilder @帶心情去旅行 中有很清楚的講解,你們去原做者家查閱便可。spa