Different colors at EditText in Android

2019-02-10 23:25发布

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 the rest red?

4条回答
Emotional °昔
2楼-- · 2019-02-10 23:30

You could use spannables.

Spannable spannable = yourText.getText();
spannable .setSpan(new BackgroundColorSpan(Color.argb(a, r, g, b)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
查看更多
Juvenile、少年°
3楼-- · 2019-02-10 23:34

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-10 23:39

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);
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-10 23:51

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
查看更多
登录 后发表回答