实现效果:文本部分文字可点击
效果.png1.添加点击:
binding.tvAgree.setText("已阅读并同意");
SpannableString ssPri = new SpannableString("《用户服务协议》");
ssPri.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
Toast.makeText(LoginActivity.this, "用户服务协议", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(this, PrivateActivity.class));
}
}, 0, ssPri.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
binding.tvAgree.append(ssPri);
//处理点击后Span变色
binding.tvAgree.setHighlightColor(getResources().getColor(android.R.color.transparent));
STEP1.png
2.去除下划线:
···
ssPri.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
Toast.makeText(LoginActivity.this, "用户服务协议", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(this, PrivateActivity.class));
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(ds.linkColor); //设置颜色
ds.setUnderlineText(false); //去除下划线
}
}, 0, ssPri.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
···
STEP2.png
3.点击事件冲突:
点击富文本时,同时会触发TextView/LinearLayout的点击事件。
案例的布局为LinearLayout包含CheckBox和TextView,LinearLayout点击事件触发CheckBox点击事件,TextView无点击事件。
binding.llAgree.setOnClickListener(v -> binding.cbAgree.performClick());
此时,点击文本时,ClickableSpan和LinearLayout的点击事件同时触发。
通过setMovementMethod
处理点击事件
binding.tvAgree.setMovementMethod(new LinkMovementMethod() {
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
// 因为TextView没有点击事件,所以点击TextView的非富文本时,super.onTouchEvent()返回false;
// 此时可以让TextView的父容器执行点击事件;
boolean isConsume = super.onTouchEvent(widget, buffer, event);
if (!isConsume && event.getAction() == MotionEvent.ACTION_UP) {
ViewParent parent = widget.getParent();
if (parent instanceof ViewGroup) {
// 获取被点击控件的父容器,让父容器执行点击;
((ViewGroup) parent).performClick();
}
}
return isConsume;
}
});
完整CODE:
binding.tvAgree.setText("已阅读并同意");
SpannableString ssPri = new SpannableString("《用户服务协议》");
ssPri.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
Toast.makeText(LoginActivity.this, "用户服务协议", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(this, PrivateActivity.class));
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
// ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
}
}, 0, ssPri.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
binding.tvAgree.setMovementMethod(new LinkMovementMethod() {
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
boolean isConsume = super.onTouchEvent(widget, buffer, event);
if (!isConsume && event.getAction() == MotionEvent.ACTION_UP) {
ViewParent parent = widget.getParent();
if (parent instanceof ViewGroup) {
// 获取被点击控件的父容器,让父容器执行点击;
((ViewGroup) parent).performClick();
}
}
return isConsume;
}
});
binding.tvAgree.append(ssPri);
//处理点击后Span变色
binding.tvAgree.setHighlightColor(getResources().getColor(android.R.color.transparent));
网友评论