我想在AlertDialogwindow中单击文本时打开电子邮件客户端。我使用Setspan方法和Linkify但没有结果。这是我的代码:
SpannableString s = new SpannableString("contact");
s.setSpan(new URLSpan("http://www.google.com"), 0, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
final TextView tx1 = new TextView(this);
tx1.setText(getString(R.string.locerstatus) +s);
tx1.setAutoLinkMask(RESULT_OK);
tx1.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(s, Linkify.EMAIL_ADDRESSES);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) { }
})
.setView(tx1).show();
答案 0 :(得分:2)
尝试以这种方式使用ClickableSpan:
final TextView tx1 = new TextView(this);
tx1.setAutoLinkMask(RESULT_OK);
tx1.setMovementMethod(LinkMovementMethod.getInstance());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
})
.setView(tx1);
final AlertDialog dialog = builder.create();
String sourceString = "This is test string with contact word";
String keyWord = "contact";
SpannableString spannableString = new SpannableString(sourceString);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some@email.address" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
dialog.dismiss();
}
};
spannableString.setSpan(clickableSpan, sourceString.indexOf(keyWord), sourceString.indexOf(keyWord) + keyWord.length(), 0);
tx1.setText(spannableString);
dialog.show();
<强>更新强>
如果您想更改可点击文字的颜色您还应该覆盖updateDrawState()
ClickableSpan()
方法,如下所示:
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some@email.address" });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
dialog.dismiss();
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLUE);
ds.setUnderlineText(true);
}
};