我有一个像这样的 3 字符串:
"@Username: Deliverd your order",
"YOU got trophy: KING OF COINS",
"There is a package waiting for you to pick up from #surat to #mumbai",
我想做的是通过点击事件获得不同颜色的用户名和城市名称。
我能够实现的是通过拆分为“:”字符来获取用户名。 但我不知道如何获取城市名称和两者的点击事件。
在城市名称中只有最后一个城市颜色在改变,如何改变城市名称颜色并获得其点击事件。
这是我尝试过的:
if (notifications.getTitle().contains(":"))
{
String[] username = notifications.getTitle().split(":");
String uname = getColoredSpanned(username[0] + ":", "#ff7505");
String txt = getColoredSpanned(username[1], "#000000");
holder.txtTitle.append(Html.fromHtml(uname +" " + txt));
holder.txtTitle.setMovementMethod(LinkMovementMethod.getInstance());
}
else if (notifications.getTitle().contains("#"))
{
Matcher matcher =
Pattern.compile("#\\s(\\w+)").matcher(notifications.getTitle());
i=0;
while (matcher.find())
{
place.add(i, matcher.group(1));
i++;
}
String place1 = getColoredSpanned("#" + place.get(0), "#237BCD");
String place2 = getColoredSpanned("#" + place.get(1), "#237BCD");
places1 = notifications.getTitle().replace("#" + place.get(0), place1);
places1 = notifications.getTitle().replace("#" + place.get(1), place2);
holder.txtTitle.setText(Html.fromHtml(places1));
}
else
{
holder.txtTitle.setText(notifications.getTitle());
}
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
这就是我得到的输出:
这是我真正期望的:
最佳答案
我认为您已经完成了用户名的设置,并且在点击城市时遇到了问题,所以我通过点击城市名称给出了答案。
感谢@Vinay 提供了一些提示。
请检查下面的代码。
public void setSpan() {
String test = "There is a package waiting for you to pick up from #surat to #mumbai";
SpannableString spannable = new SpannableString(test);
final Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(test);
while (matcher.find()) {
final String city = matcher.group(1);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
Toast.makeText(mActivity, city, Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(Color.RED);
}
};
int cityIndex = test.indexOf(city) - 1;
spannable.setSpan(clickableSpan, cityIndex, cityIndex + city.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mTextViewNotification.setText(spannable);
mTextViewNotification.setMovementMethod(LinkMovementMethod.getInstance());
}
输出截图:
关于android - 如何获取word中的特殊字符及其点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051436/