猿问

如何将文本效果应用于 { } 大括号内的单词

我有来自 SQLite 数据库的文本以这种形式发送到我的 onBindViewHolder:你好,我是 {Alex}。我希望能够调整{}内文本的大小或颜色,并在输出中隐藏那些{}花括号。所以最后希望有这样的文字:你好,我是亚历克斯

我第一次遇到与 Regex 相关的事情,谁能给我一步一步地指导如何实现这一点。

但我不明白在我的情况下我应该如何处理“ (?<=[)(.*?)(?=]) ”。


现在我的 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"));

胡说叔叔
浏览 124回答 1
1回答

慕容3067478

我不擅长正则表达式。但这里是您问题的答案,可以让您获得所需的结果(获取表达式文本并相应地对其进行格式化)。public CharSequence getFormattedQuestion(Context context, String originalQues, @ColorRes int colorToSet, @DimenRes int textSize) {&nbsp; &nbsp; // First we check if the question has the expression&nbsp; &nbsp; if (originalQues == null || !originalQues.contains("{") || !originalQues.contains("}")) {&nbsp; &nbsp; &nbsp; &nbsp; return originalQues;&nbsp; &nbsp; }&nbsp; &nbsp; // Then we break the original text into parts&nbsp; &nbsp; int startIndex = originalQues.indexOf("{");&nbsp; &nbsp; int endIndex = originalQues.indexOf("}");&nbsp; &nbsp; // 1) The text before the expression&nbsp; &nbsp; String leftPart = startIndex>0 ? originalQues.substring(0, startIndex) : "";&nbsp; &nbsp; // 2) The text after the expression (if there is any)&nbsp; &nbsp; String rightPart = endIndex == originalQues.length()-1 ? "" : originalQues.substring(endIndex+1);&nbsp; &nbsp; // 3) The expression text&nbsp; &nbsp; String midPart = originalQues.substring(startIndex+1, endIndex);&nbsp; &nbsp; // 4) Format the mid part with the give color (colorToSet) and size (textSize)&nbsp; &nbsp; SpannableString spannableMid = new SpannableString(midPart);&nbsp; &nbsp; spannableMid.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorToSet)), 0, midPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);&nbsp; &nbsp; spannableMid.setSpan(new AbsoluteSizeSpan(context.getResources().getDimensionPixelSize(textSize)), 0, midPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);&nbsp; &nbsp; // check if there is any left part; if so, add it with mid&nbsp; &nbsp; CharSequence leftAndMid = leftPart.length()>0 ? TextUtils.concat(leftPart, " ", spannableMid) : spannableMid;&nbsp; &nbsp; // Check if there is any right part else return the left and mid&nbsp; &nbsp; return rightPart.length()>0 ? TextUtils.concat(leftAndMid, " ", rightPart) : leftAndMid;}所以基本上我们将原始问题分成 3 个部分。第一部分,表达前的文字。第 2 部分表达式文本。第 3 部分表达式后的文本。然后我们使用SpannableString. 然后我们通过组合所有三个来返回一个新文本。然后你可以像这样使用它CharSequence ques = getFormattedQuestion(holder.itemView.getContext(), question.getQuestion(), R.color.blue, R.dimen.text_size);holder.tvQuestion.setText(ques);
随时随地看视频慕课网APP

相关分类

Java
我要回答