如何链接AlertDialog中的部分消息?
How to linkify a part of the message in AlertDialog?
是否可以将部分对话消息设为 link?并为该部分分配一个点击侦听器?
假设我有一个这样的对话框:
String message = "Hello, click here for more info";
String messageClickable = "click here";
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("Ok", null)
.show();
如何使 messageClickable
部分可点击?我研究了 class Linkify
但我只能找到适用于实际 link 或 phone 数字等的方法 addLinks
我最终使用的解决方案如下:
private void showDialogWithClickableMessage() {
String message = "Hello, click here for more info";
String messageClickable = "click here";
SpannableString messageSpannable = new SpannableString(message);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
// do something
}
};
messageSpannable.setSpan(clickableSpan, message.indexOf(messageClickable), message.indexOf(messageClickable) + messageClickable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setMessage(messageSpannable)
.setNegativeButton(R.string.alert_action_ok, null)
.show();
((TextView)alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
是否可以将部分对话消息设为 link?并为该部分分配一个点击侦听器?
假设我有一个这样的对话框:
String message = "Hello, click here for more info";
String messageClickable = "click here";
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("Ok", null)
.show();
如何使 messageClickable
部分可点击?我研究了 class Linkify
但我只能找到适用于实际 link 或 phone 数字等的方法 addLinks
我最终使用的解决方案如下:
private void showDialogWithClickableMessage() {
String message = "Hello, click here for more info";
String messageClickable = "click here";
SpannableString messageSpannable = new SpannableString(message);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
// do something
}
};
messageSpannable.setSpan(clickableSpan, message.indexOf(messageClickable), message.indexOf(messageClickable) + messageClickable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setMessage(messageSpannable)
.setNegativeButton(R.string.alert_action_ok, null)
.show();
((TextView)alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}