作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个句子包含要发布到服务器的消息,例如哇!很棒的照片 #superb #pic#111 #222 喜欢这张照片
我想提取 hastags
并使它们着色并保持其余文本不变。
我尝试了以下代码,但没有用。
private void spannableOperationOnHastag() {
mPostMessage = edPostMessage.getText().toString().trim();
String strPreHash = null;
String strHashText = "";
if (mPostMessage.contains("#")) {
try {
int index = mPostMessage.indexOf("#");
strPreHash = mPostMessage.substring(0, index);
SpannableString spannableString = new SpannableString(strPreHash);
String strHashDummy=mPostMessage.substring(index, mPostMessage.length());
int hashCount= StringUtils.countMatches(strHashDummy, "#"); // check for number of "#" occurrence and run forloop for getting the number of hastags in the string
int hasIndex=0;
for (int i = 0; i <hashCount ; i++) {
strHashText = strHashText+strHashDummy.substring(hasIndex, strHashDummy.indexOf(' '))+" ";
hasIndex =strHashText.indexOf(" "); // updating new space(" ") position in the index variable
}
SpannableString spannableStringBlue = new SpannableString(strHashText);
spannableStringBlue.setSpan(new ForegroundColorSpan(PublishPostActivity.this.getResources().getColor(R.color.blue)), 0, strHashText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
} catch (Exception e) {
Log.d(TAG, "validatePostMessage() called with " + "e = [" + e + "]");
}
}
}
最佳答案
我自己解决了这个问题。我需要它的任何人都可以引用此代码:)
private void spannableOperationOnHastag() throws Exception{
mPostMessage = edPostMessage.getText().toString()+" "; // extra space for spannable operations
List<Integer> listStartPos = new ArrayList<>();
List<Integer> listEndtPos = new ArrayList<>();
if (mPostMessage.contains("#")){
for (int i = 0; i < mPostMessage.length(); i++) {
if (mPostMessage.charAt(i) == '#') {
listStartPos.add(i);
Log.d(TAG, "startIndex of # = " + i);
}
}
for (int i = 0; i < listStartPos.size(); i++) {
int endIndex = mPostMessage.indexOf(' ', listStartPos.get(i));
listEndtPos.add(endIndex);
Log.d(TAG, "endIndex of # " + (endIndex));
}
SpannableString spanned = SpannableString.valueOf(mPostMessage);
for (int i = 0; i < listStartPos.size(); i++) {
spanned = new SpannableString(spanned);
spanned.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), listStartPos.get(i), listEndtPos.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.d(TAG, "substring " + mPostMessage.substring(listStartPos.get(i), listEndtPos.get(i) + 1));
}
mPostMessage.trim(); // removing extra space.
edPostMessage.setText(null);
edPostMessage.setText(spanned);
}
}
关于java - 如何在android中部分改变文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836448/
我是一名优秀的程序员,十分优秀!