Android Textview 動態 部分文字點選 改變顏色
最近現在專案中遇到了一個需求 ,就是部分文字可以點選和改變顏色 ,這其實還是ok的 不是什麼變態需求 因為也沒有做過 我感覺textview 自己就會有實現此需求的辦法 一百度還真有
廢話不多說 開始上程式碼
public class MainActivity extends AppCompatActivity {
@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, 10, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(style);
//設定部分文字顏色
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
style.setSpan(foregroundColorSpan, 10, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//配置給TextView
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(style);
}
}
但是這樣寫的話確實很快實現了該效果
但是複用性不是很高 而且我現在不知道後臺返給我的具體的String是什麼 只知道點選的是確定的 所以我有進一步的優化了這個方法
/**
*
* @author 大聖
* @time 2018/10/17 下午3:51
* @param content 全部的文字
* @param str 點選文字
* @param len 點選文字的長度
* @param textView 元件textview
* @param mListeners 介面回撥
* @param type 分辨是哪個
*/
private void callService(String content, String str,int len , TextView textView ,final MyDialogListener mListeners ,final int type) {
SpannableStringBuilder builder =new SpannableStringBuilder(content);
int i = content.indexOf(str);//擷取文字開始的下標
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
//點選後的操作
if (type ==1) {
mListeners.onClicktoH5();
}
if (type ==2) {
mListeners.onClicktoMy();
}
// CommonUtils.call(mContext, "12351");
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.parseColor("#0000FF"));//設定文字顏色
ds.setUnderlineText(true);//設定下劃線//根據需要新增
}
}, i, i + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(builder);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
嘻嘻 這個方法是我自己優化過後的 具體的傳參註釋也有 菜鳥亦可以明白其中的邏輯 也可以根據自己的需求來改 嘻嘻 都半年多沒有寫部落格了 我又開始強勢的迴歸了