I am trying to change the text color by simply clicking the button but when I click the button it changes the previously typed text color also. Means changes the whole text color. When I try to change color through Spannable then it changes the color of the selected part of the text but not for the text which I am going to type next. Is there a way where I can click the button and it does not change the whole text color but the color for which I type next. Thanks
here is what I know only
redtxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
str.setSpan(new ForegroundColorSpan(Color.parseColor(txtColor)), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setTextColor(Color.parseColor("#d32f2f"));
}
});
you can use SpannableString
for example:
final SpannableString text = new SpannableString("Hello stackOverflow");
text.setSpan(new RelativeSizeSpan(1.5f), text.length() - "stackOverflow".length(), text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new ForegroundColorSpan(Color.RED), 3, text.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(text);
get your whole text into Spannable like
Spannable text = edittext.getText();
After that just do.
if (edittext.getText().length() != 0){
text.setSpan(new ForegroundColorSpan(YOUR_COLOR), selection_start, selection_end, 34);
}
You need to implement Spannable String builder(Global Object) and on onChangeText event just append spanned string to Spannable String builder.
SpannableStringBuilder objSpannableStringBuilder;
edt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
final SpannableString text = new SpannableString(s.toString());
text.setSpan(new ForegroundColorSpan(Color.RED), 3, text.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); objSpannableStringBuilder.append(text);
your_edit_text.setText(objSpannableStringBuilder);
}
@Override
public void afterTextChanged(Editable s) {
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.