[英]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.