Skip to content Skip to sidebar Skip to footer

Different Colors At EditText In Android

I am trying to make the text of an EditText multiple colors. For example, if my text is, 'It is a good day.', is it possible to make the 'It is a' part of the sentence green and th

Solution 1:

I use something like that to make some parts of my color green:

final String text = "Some Text";
Spannable modifiedText = new SpannableString(text);
modifiedText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green)), 0, lengthYouWant, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(modifiedText);

Solution 2:

I'm have this trouble too. After several hours, I figured out how to handle it:

  mYourTextView.addTextChangedListener(new TextWatcher() {

        private String oldContent = "";

        @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 String newContent = mYourTextView.getText().toString();

            if (newContent.length() > 10 && !oldContent.equals(newContent)) {
                oldContent = newContent;
                mYourTextView.setText(Html.fromHtml(
                        String.format("%s", "<font color='#000000'>" + newContent.substring(0, 10) + "</font>")
                                + "<font color='#ff0000'>" + newContent.substring(10, newContent.length()) + "</font>"));
                Log.d("onTextChanged", "Start : " + start);

                //move cursor after current character
                mYourTextView.setSelection(start + 1 > mYourTextView.getText().toString().length()
                        ? start : start + 1);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

This code make first 10 characters in black color and the followed characters in red color. We need variable oldContent to prevent loop infinity because when EditText call setText() then onTextChanged


Solution 3:

Yes. You will need to create a Spannable object (either a SpannedString or SpannedStringBuilder), then set spans upon it to apply the colors you seek.

For example, the following method from this sample project takes the contents of a TextView, searches for a user-entered string, and marks up all occurrences with a purple background color, removing all previous markers:

  private void searchFor(String text) {
    TextView prose=(TextView)findViewById(R.id.prose);
    Spannable raw=new SpannableString(prose.getText());
    BackgroundColorSpan[] spans=raw.getSpans(0,
                                             raw.length(),
                                             BackgroundColorSpan.class);

    for (BackgroundColorSpan span : spans) {
      raw.removeSpan(span);
    }

    int index=TextUtils.indexOf(raw, text);

    while (index >= 0) {
      raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
          + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      index=TextUtils.indexOf(raw, text, index + text.length());
    }

    prose.setText(raw);
  }

In your case, changing the foreground color would use a ForegroundColorSpan instead of a BackgroundColorSpan.

Things get a bit tricky with an EditText, in that the user can edit the text, and you will need to choose your flags to meet the rules you want. For example, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE would say that:

  • characters entered in the middle of the spanned area get the span's effect (e.g., foreground color)
  • characters entered immediately before or after the spanned area are considered outside the spanned area and therefore do not get the span's effect

Solution 4:

Just to elaborate on the answer of WarrenFaith:

implement a TextWatcher

yourEditText.onFocusChangeListener = this

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
    val newTextStyle: Spannable = SpannableString(s?.toString())
    resources.getColor(R.color.color_w3w, requireActivity().theme)
    val span = ForegroundColorSpan(resources.getColor(R.color.your_color_here, requireActivity().theme))
    newTextStyle.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)//Will set the first three characters to 'R.color.your_color_here'
    s?.set(0, 3, span)
}

Post a Comment for "Different Colors At EditText In Android"