[英]not able to change color of a part of text in EditText
I want to change the color of some part of text in EditText. 我想更改EditText中某些文本的颜色。 I am trying following code, but it is not working.
我正在尝试遵循以下代码,但无法正常工作。
SpannableStringBuilder ssb=new SpannableStringBuilder(expression);
ForegroundColorSpan fcs=new ForegroundColorSpan(Color.rgb(181,1,1));
ssb.setSpan(fcs,startIndex,endIndex,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
expressionEditText.setText(ssb);
expressionTextView.setText(ssb);
startIndex
andendIndex
are the indices in the expression for which the color needs to be changed.startIndex
和endIndex
是表达式中需要更改颜色的索引。This code works fine for the 'expressionTextView' but not for 'expressionEditText'.
这段代码适用于'expressionTextView',但不适用于'expressionEditText'。
xml part: xml部分:
<EditText
android:id="@+id/expression_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_above="@id/expression_text_view"
android:gravity="bottom|end"
android:includeFontPadding="false"
android:textSize="45sp"
android:background="@android:color/transparent"
android:inputType="text"/>
<TextView
android:id="@+id/expression_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:gravity="right"
android:textSize="50sp"/>
example: 例:
expression="I want color to be changed";
startIndex=2;
endIndex=5;
In expressionTextView "wan" color will be the specified color. 在expressionTextView中,“ wan”颜色将是指定的颜色。 In expressionEditText there will not be any color change.
在expressionEditText中,不会有任何颜色变化。
This is very simple. 这很简单。
As i answered before in this question . 正如我之前在这个问题上回答的那样。
You can achieve this by the following code, which i use always. 您可以通过以下代码(我一直使用)来实现这一点。 I tried to make this method as simple as i could.
我试图使这种方法尽可能简单。 You have to pass just your
Editext
and TextToHighLight
in below method. 您只
TextToHighLight
在以下方法中传递Editext
和TextToHighLight
。
If you require clickable span you can go to my answer . 如果您需要可点击范围,可以转到我的答案 。 Feel free to ask in comment if you need TextWatcher too.
如果您也需要TextWatcher,请随时发表评论。
public void setHighLightedText(EditText editText, String textToHighlight) {
String tvt = editText.getText().toString();
int ofe = tvt.indexOf(textToHighlight, 0);
Spannable WordtoSpan = new SpannableString(editText.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.