是否可以将 EditText 中的部分文字作为一种颜色而另一部分作为另一种颜色?
答案 0 :(得分:1)
我有一个使用Html的示例,但您可以轻松地更改它
String text = "<p>Hello world</p>";
// create Spanned
Spanned spanned = Html.fromHtml(text);
// create SpannableString
SpannableString spanString = new SpannableString(spanned);
// set colored part
ClickableSpan coloredPart = new ClickableSpan() {
@Override
public void onClick(View textView) {
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(Color.WHITE);
}
};
spanString.setSpan(coloredPart, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setText(spanString, TextView.BufferType.SPANNABLE);
答案 1 :(得分:0)
当然没问题。
TextAppearanceSpan mHighlightTextSpan = new TextAppearanceSpan(mContext, R.style.searchTextHighlight);
int startOfTextSearchTeam = orderModel.getTitle() != null ? indexOfSearchTermFromName(orderModel.getTitle()) : -1; //simple search for string in string for index
final SpannableString highlightTitle = new SpannableString(orderModel.getTitle() + " " + mContext.getString(R.string.count_open_bracket) + orderModel.getImageCount() + mContext.getString(R.string.count_closed_bracket));
// Sets the span to start at the starting point of the match and end at "length"
// characters beyond the starting point
if(startOfTextSearchTeam != -1){
highlightTitle.setSpan(mHighlightTextSpan, startOfTextSearchTeam, startOfTextSearchTeam + mSearchTerm.length(), 0);
itemViewHolder.txtOrderTitle.setText(highlightTitle);
}
我在回收器视图适配器中执行此操作,因为我在搜索时突出显示每行的跨度,但这是相同的概念。此外,我在构造函数中只知道了一次highlightTextSpan。
希望有所帮助。古德勒克。
答案 2 :(得分:0)
您可以使用SpannableString
,试试这个。
SpannableString spannableText = new SpannableString("Text default to color");
final EditText diffColor = new EditText(getActivity());
// make "Text" (characters 0 to 4) red
spannableText.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0);
diffColor.setText(spannableText, TextView.BufferType.SPANNABLE);
答案 3 :(得分:0)
试试这个。它会起作用......
EditText edtText=(EditText)findViewById(R.id.edtText);
SpannableStringBuilder sb = new SpannableStringBuilder("Hello world in android");
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.RED);
// code to specify the character which do you want to change color. In this I have set value from 0,4 to change the color of firts 4 character from string.
sb.setSpan(fcs,0,4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
edtText.setText(sb);