繁体   English   中英

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

[英]How apply text effects to a word inside { } curly braces

我有来自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"));

在此处输入图片说明

我对正则表达式不好。 但是,这里是您问题的答案,它将使您获得所需的结果(获取表达式文本并相应地设置其格式)。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM