我有来自 SQLite 数据库的文本,格式如下:你好,我是 {Alex}。 我希望能够调整 {} 内文本的大小或颜色,并在输出中隐藏这些 {} 花括号。所以最终希望有这样的文字:你好,我是亚历克斯
这是我第一次遇到与正则表达式相关的事情,任何人都可以给我简短的分步指导如何完成此任务。
我发现类似的问题:
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;
}
所以基本上我们将原始问题分为 3 部分。第一部分,表达前的文本。第2部分表达文本。第3部分表达式后的文本。然后,我们使用 SpannableString 设置颜色和大小的表达式文本(第 2 部分)的格式。然后我们通过组合这三个文本来返回一个新文本。
然后你就可以像这样使用它
CharSequence ques = getFormattedQuestion(holder.itemView.getContext(), question.getQuestion(), R.color.blue, R.dimen.text_size);
holder.tvQuestion.setText(ques);
关于java - 如何将文本效果应用于 { } 大括号内的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687687/