亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將文本效果應用于 { } 大括號內的單詞

如何將文本效果應用于 { } 大括號內的單詞

胡說叔叔 2021-11-03 14:55:58
我有來自 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"));
查看完整描述

1 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

我不擅長正則表達式。但這里是您問題的答案,可以讓您獲得所需的結果(獲取表達式文本并相應地對其進行格式化)。


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. 然后我們通過組合所有三個來返回一個新文本。

然后你可以像這樣使用它


CharSequence ques = getFormattedQuestion(holder.itemView.getContext(), question.getQuestion(), R.color.blue, R.dimen.text_size);

holder.tvQuestion.setText(ques);


查看完整回答
反對 回復 2021-11-03
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號