Edittext With Different Color In Android
Am facing some problem with edit text, actually what I need is 1st 10 letters typed should be in red colour and the letter's typed after this should be in grey colour. I did with t
Solution 1:
Try this code (I've tested it and works as expected):
finalEditTextinput= (EditText) findViewById(R.id.my_edittext);
input.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {}
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
Spannablespannable= input.getText();
if (!TextUtils.isEmpty(s) && s.length() > 9){
spannable.setSpan(newForegroundColorSpan(ContextCompat.getColor(MainActivity.this, R.color.my_color_red)),
0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
@OverridepublicvoidafterTextChanged(Editable s) {}
});
Solution 2:
Try using Spannable
Spannablespannable= myEditText.getText();
spannable.setSpan(newForegroundColorSpan(getResources().getColor(R.color.red)), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Solution 3:
Use Spannable
String for this as
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString redSpannable= new SpannableString("yourstring");
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 11, 0);
builder.append(redSpannable);
SpannableString whiteSpannable= new SpannableString("next string");
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 11, 20, 0);
builder.append(whiteSpannable);
editText.setText(builder, BufferType.SPANNABLE);
Post a Comment for "Edittext With Different Color In Android"