0

I want the change the color of an android EditText if text contains '(' and ')'. Brackets have special meaning and that string need to change the color. Please anyone help.

pcbabu
  • 2,219
  • 4
  • 22
  • 32
  • u mean change color of the letters? – KOTIOS Dec 24 '13 at 18:44
  • 1
    Follow this question. Seems to be doing same thing. http://stackoverflow.com/questions/18055104/set-text-color-for-a-specific-text-in-android-edittext – thestar Dec 24 '13 at 19:03
  • possible duplicate of [How to set text color of TextView in code?](http://stackoverflow.com/questions/4602902/how-to-set-text-color-of-textview-in-code) – zed_0xff Dec 25 '13 at 06:26

5 Answers5

3

use TextWatcher for EditText

example

editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(s)) {
                String text = s.toString();
                if(text.contains("(") || text.contains(")")) {
                    editText.setTextColor(Color.RED);
                } else {
                    editText.setTextColor(Color.BLACK);
                }
            }
        }
    });
Gopal Gopi
  • 11,101
  • 1
  • 30
  • 43
1

EditText extends TextView which has a method called setTextColor(int color)

See Documentation

Andrew Orobator
  • 7,978
  • 3
  • 36
  • 36
1
   topic.setTextColor(Color.RED);   

  topic.setTextColor(Color.parseColor("#ffff0000"));
keshav
  • 3,235
  • 1
  • 16
  • 22
1

You can do something like this:

text.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        if(s.toString().contains("(") && s.toString().contains(")")){
            EditText text = (EditText) findViewById(R.id.id_of_text);
            text.setTextColor(color);
        }
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Note that you don't want to call findViewById() every time the text changes as it's pretty slow, so store that reference globally.

Edit: please note that the parameter color in setTextColor() is a color, and not a resource. So to get a color from the resource you need to use the following:

getResources().getColor(R.color.color_id);
Jeffrey Klardie
  • 3,020
  • 1
  • 18
  • 23
1

Have you looked at TextWatcher? (link)

You can inspect the entered string after every change, and format it as you see fit.

Collin Flynn
  • 751
  • 6
  • 8