我有来自SQLite数据库的文本以这种形式发送到onBindViewHolder:您好,我是{Alex}。
我希望能够调整{}中文本的大小或颜色,并从输出中隐藏这些{}大括号。所以最终希望拥有这样的文本:你好,我是亚历克斯
我第一次遇到与Regex有关的东西时,有人可以一步一步地指导我如何完成此操作。
我发现了类似的问题:
Regular Expression to find a string included between two characters while EXCLUDING the delimiters
但是我不明白我应该如何处理“(?
现在我的onBindViewHolder看起来像这样:
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Question question = questionList.get(position);
holder.tvQuestion.setText(question.getQuestion());
// holder.tvQuestion.setTextColor(Color.parseColor("#ff0099cc"));
最佳答案
我对正则表达式不好。但是,这里是您问题的答案,它将使您获得所需的结果(获取表达式文本并相应地设置其格式)。
public CharSequence getFormattedQuestion(Context context, String originalQues, @ColorRes int colorToSet, @DimenRes int textSize) {
// First we check if the question has the expression
if (originalQues == null || !originalQues.contains("{") || !originalQues.contains("}")) {
return originalQues;
}
// Then we break the original text into parts
int startIndex = originalQues.indexOf("{");
int endIndex = originalQues.indexOf("}");
// 1) The text before the expression
String leftPart = startIndex>0 ? originalQues.substring(0, startIndex) : "";
// 2) The text after the expression (if there is any)
String rightPart = endIndex == originalQues.length()-1 ? "" : originalQues.substring(endIndex+1);
// 3) The expression text
String midPart = originalQues.substring(startIndex+1, endIndex);
// 4) Format the mid part with the give color (colorToSet) and size (textSize)
SpannableString spannableMid = new SpannableString(midPart);
spannableMid.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorToSet)), 0, midPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableMid.setSpan(new AbsoluteSizeSpan(context.getResources().getDimensionPixelSize(textSize)), 0, midPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// check if there is any left part; if so, add it with mid
CharSequence leftAndMid = leftPart.length()>0 ? TextUtils.concat(leftPart, " ", spannableMid) : spannableMid;
// Check if there is any right part else return the left and mid
return rightPart.length()>0 ? TextUtils.concat(leftAndMid, " ", rightPart) : leftAndMid;
}
因此,基本上我们将原始问题分为三个部分。第一部分,表达前的文字。第2部分表达文字。第三部分表达式后的文字。然后,使用
SpannableString
用颜色和大小设置表达式text(Part2)的格式。然后,我们通过将所有三个结合起来返回一个新文本。然后可以像这样使用它
CharSequence ques = getFormattedQuestion(holder.itemView.getContext(), question.getQuestion(), R.color.blue, R.dimen.text_size);
holder.tvQuestion.setText(ques);