[英]Dynamically Change TextView Background color in onclicklistener in android
[英]Adding OnTouch and OnClickListener to the links in a TextView and changing background color of the link
我有一个textview和链接。 我希望在触摸链接时突出显示这些链接,并且在长按它们时也想打开一个Alertdialog。 我尝试通过自定义URLSpan达到解决方案,但是,由于在调用OnClick之前无法访问mView,因此无法设置侦听器:
class ConfirmSpan extends URLSpan{
View mView;
URLSpan span;
public ConfirmSpan(URLSpan span) {
super(span.getURL());
this.span = span;
//there is a nullpointerexception here since mView is null now.
mView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
((TextView)v).setBackgroundColor(0xcccccccc);
return false;
}
});
//this is also an exception
mView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.d("INFO","long click yay!");
return false;
}
});
}
//this should be called to reach the view. But then I can't handle touch state.
@Override
public void onClick(View widget) {
mView = widget;
//bla bla..
}
public void openURL() {
super.onClick(mView);
}
}
我认为我必须自定义LinkMovementMethod类,但是如何? 任何意见将不胜感激。 更新:我现在可以使用以下代码处理触摸事件:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod sInstance;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
// Here I am changing backgorund color
if(event.getAction() == MotionEvent.ACTION_DOWN)
widget.setBackgroundColor(0xcccccccc);
if(event.getAction() == MotionEvent.ACTION_UP)
widget.setBackgroundColor(0xffffffff);
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new CustomLinkMovementMethod();
return sInstance;
}
}
但是,TextView命名为小部件(参数OnTouchEvent())不是我想要的。 这是全部文字。 因此,当我触摸链接时,文本将全部变为灰色。 我想我需要其他一些方法,例如通过查找链接的开始和结束线的坐标来为链接的背景着色。
感谢您提出这个问题,我想我可能会为您提供解决方案。
在https://gist.github.com/qtyq/90f9b4894069a8b3676c中查看代码
它是SpannableString的工厂帮助程序类,它允许您通过以下方式轻松创建SpannableString:
这是一个用法示例:
SpannableString ss = SpannableBuilder.init(bottomText)
.setColor("Terms & Conditions", getResources().getColor(R.color.orange))
.makeLink(getContext(), "Terms & Conditions", terms)
.setColor("Privacy Policy", getResources().getColor(R.color.orange))
.makeLink(getContext(), "Privacy Policy", policy)
.create();
textView1.setText(ss);
当然,您可以自定义该类中的方法,或者如果需要进一步自定义,则可以添加自己的方法,只需阅读Google的SpannableString文档,以获取有关您可以执行的操作的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.