我们知道使用SpannableString和ClickableSpan可以实现部分文字高亮点击效果,但是设置了setMovementMethod(LinkMovementMethod.getInstance())会使文字自带滑动。最近有个需求是在Dialog中显示高亮可点击跳转的文字,但是受Dialog大小限制,需要添加ScrollView以上下滑动,这样就会出现滑动冲突,参考一些资料后琢磨出了解决方案。
ps:setMovementMethod(LinkMovementMethod.getInstance())不是自带滑动效果吗?为啥还用ScrollView包一层?实际上这个自带点击的滑动效果贼垃圾,一碰就触发点击了,根本不滑,谁用谁知道
看下效果
贴出主要代码
1、高亮文字和点击跳转——自定义Span
public class CustomSpan extends URLSpan {
public Context mContext;
public String mId;
public CustomSpan(String url) {
super(url);
}
public CustomSpan(String url, Context context, String id) {
super(url);
this.mContext = context;
this.mId = id;
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.parseColor("#5F7AB8"));
ds.setUnderlineText(false);
}
@Override
public void onClick(View widget) {
if (!TextUtils.isEmpty(mId)) {
Intent intent = new Intent(mContext, XXX.class);
intent.putExtra("id", mId);
mContext.startActivity(intent);
}
}
/**
*
* @param context
* @param spannableContent 要匹配的高亮可点击内容
* @param content 全文
* @param id
* @return
*/
public static SpannableString getSpannableContent(Context context, SpannableString spannableContent, String content, String id) {
Pattern pattern = Pattern.compile(content, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(spannableContent);
while (matcher.find()) {
URLSpan span = new CustomSpan(content, context, id);
spannableContent.setSpan(span, matcher.start(0), matcher.end(0), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableContent;
}
}
获取Dialog中要显示的内容,Conflict对象中有id和name,具体我就不写了
private SpannableString getConflictMessage(List<Conflict> conflicts) {
String str = "与{count}个计划{name}时间冲突,确认接受?";
str = str.replace("{count}", conflicts.size() + "");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < conflicts.size(); i++) {
sb.append("【").append(conflicts.get(i).getName()).append("】");
if (i != conflicts.size() - 1) {
sb.append("、");
}
}
str = str.replace("{name}", sb);
SpannableString ss = new SpannableString(str);
for (int i = 0; i < conflicts.size(); i++) {
StringBuilder match = new StringBuilder();
match.append("【").append(conflicts.get(i).getName()).append("】");
if (i != conflicts.size() - 1) {
match.append("、");
}
ss = CustomSpan.getSpannableContent(mContext, ss, match.toString(), String.valueOf(conflicts.get(i).getId()));
}
return ss;
}
再给TextView加上tv.setMovementMethod(LinkMovementMethod.getInstance());就实现了部分文字高亮点击跳转
2、滑动冲突处理——自定义MovementMethod
这里就是复制修改下LinkMovementMethod的源码,把滑动部分去掉就可以了,LinkMovementMethod的源码就不贴了,用到时自己对照查看,这里只贴CustomMovementMethod代码
public class CustomMovementMethod extends BaseMovementMethod {
private static CustomMovementMethod customMovementMethod;
public static CustomMovementMethod getInstance() {
if (customMovementMethod == null) {
synchronized (CustomMovementMethod .class) {
if (customMovementMethod == null) {
customMovementMethod = new CustomMovementMethod ();
}
}
}
return customMovementMethod;
}
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
// 只处理点击事件
link[0].onClick(widget);
}
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
private CustomMovementMethod () {
}
}
这样在ScrollView中的TextView就可以滑动了
3、Dialog大小适配——自定义可设置最大高度的ScrollView
如果Dialog中ScrollView高度写死,文字多了可视范围大,效果好,当只有一行时就尴尬了,于是就设置个最大高度吧
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
public MaxHeightScrollView(Context context) {
super(context);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
maxHeight = typedArray.getDimensionPixelSize(R.styleable.MaxHeightScrollView_max_height, 0);
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (maxHeight > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
attrs.xml中
<declare-styleable name="MaxHeightScrollView">
<attr name="max_height" format="dimension"/>
</declare-styleable>
以上几步在Dialog中使用
TextView tv = (TextView) dialog.findViewById(R.id.message);
tv.setText(getConflictMessage(conflicts));
tv.setMovementMethod(CustomMovementMethod.getInstance());
tv.setMovementMethod(CustomMovementMethod.getInstance());是重点,漏了这句点击没有效果
如果有更好的实现方法告诉下,互相学习