我想问问,如何实现Android textview的部分字体变色并且整个段落左右对齐,你们有没有类似的demo?我搞了好几天都没实现,现在参照网上的代码,实现了段落对齐,然后分开使用Android HTML解析实现了部分文字变色,但是最后把它们两融在一起的时候,颜色就失效了,这个怎么破?代码如下
= ;;TextPaint ;
String = ;
Pattern ;
Matcher ;
String[] = String[];
String[] = String[];
JustifyTextView(Context context) {
(context);
init();
}
JustifyTextView(Context context, AttributeSet attrs) {
(context, attrs);
init();
}
JustifyTextView(Context context, AttributeSet attrs, defStyleAttr) {
(context, attrs, defStyleAttr);
init();
}
init() {
= getPaint();
.setColor(getCurrentTextColor());
.= getDrawableState();
}
onDraw(Canvas canvas) {
= ;
= getMeasuredWidth();+= getTextSize();
String text = getText().toString();
Layout layout = getLayout();
lineCount = layout.getLineCount();
(i = ; i < lineCount; i++) {lineStart = layout.getLineStart(i);
lineEnd = layout.getLineEnd(i);
String lineText = text.substring(lineStart, lineEnd);(needScale(lineText)) {
(i == lineCount - ) {(lineText.indexOf() != -||lineText.indexOf() != -)
.setColor(Color.);
.setColor(Color.);
canvas.drawText(lineText, , , );
} {
(lineText.indexOf() != -||lineText.indexOf() != -)
.setColor(Color.);
.setColor(Color.);
width = StaticLayout.(text, lineStart, lineEnd, );
drawScaleText(canvas, lineText, width);
}
} {
canvas.drawText(lineText, , , );
}
+= getLineHeight();}
}
drawScaleText(Canvas canvas, String lineText, lineWidth) {
x = ;
(isFirstLineOfParagraph(lineText)) {
String blanks = ;
canvas.drawText(blanks, x, , );
width = StaticLayout.(blanks, );
x += width;
lineText = lineText.substring();
}
interval = (- lineWidth) / (lineText.length() - );
(i = ; i < lineText.length(); i++) {
String character = String.(lineText.charAt(i));
cw = StaticLayout.(character, );
canvas.drawText(character, x, , );
x += (cw + interval);
}
}
isFirstLineOfParagraph(String lineText) {
lineText.length() > && lineText.charAt() == && lineText.charAt() == ;
}
needScale(String lineText) {
(lineText.length() == ) {
;
} {
lineText.charAt(lineText.length() - ) != ;
}
}
//使用正则表达式提取关键字
setText(CharSequence text, BufferType type) {
= Pattern.();
= .matcher(text);
String s = text.toString();
(i = ; .find(); i++) {
[i] = .group().replaceAll(, );
s = s.replaceAll(, ).replace([i], );
}
text =text.toString().replaceAll(, );
.setText(text, type);
}
添加回答
举报
0/150
提交
取消