好久沒有寫文章了,最近有些時間,所以就寫了這篇文章。在寫業務的時候,經常會碰到一些這樣的需求,一個TextView中需要你高亮顯示部分重要的關鍵字,並且需要字體變的更大些,類似於下圖。
像這種需求,如果不用一個TextView來實現,來就得多個TextView控件,這樣對於性能是有些傷害的,所以纔想去寫一個滿足這種需求的TextView控件。
寫的這個自定義View是去繼承了TextView。代碼如下:
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yuzhuo on 16/9/11.
*/
public class SpannableTextView extends TextView {
private Context context;
public SpannableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public void setSpecifiedTextsColor(String text, String specifiedTexts,
int color,int textSize) {
//color is the text need change the color
List<Integer> sTextsStartList = new ArrayList<Integer>();
specifiedTexts = specifiedTexts.toLowerCase();
int sTextLength = specifiedTexts.length();
String temp = text.toLowerCase();
int lengthFront = 0;// 記錄被找出後前面的字段的長度
int start = -1;
do {
start = temp.indexOf(specifiedTexts);
if (start != -1) {
start = start + lengthFront;
sTextsStartList.add(start);
lengthFront = start + sTextLength;
temp = text.substring(lengthFront);
}
} while (start != -1);
SpannableStringBuilder styledText = new SpannableStringBuilder(text);
for (Integer i : sTextsStartList) {
styledText.setSpan(new ForegroundColorSpan(color), i, i
+ sTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if(textSize>0) {
styledText.setSpan(new AbsoluteSizeSpan(sp2px(context, textSize)), i, i
+ sTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
setText(styledText);
}
/**
* 將sp值轉換爲px值,保證文字大小不變
*
* @param spValue
* @param context
* (DisplayMetrics類中屬性scaledDensity)
* @return
*/
public int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
這個類主要是用了android.text下面的兩個類:Spannable和SpannableStringBuilder
import android.text.Spannable; import android.text.SpannableStringBuilder;
用這兩個類來實現了,針對於不同的內容來進行設置不能的textStyle,這樣便達到了這一效果。
給出實現效果圖:
這個功能比較小,但是很實用,希望對大家有幫助。