0

I want to change the background color of EditText when it is filled with input I tried for if focused I want to change for if filled also

I tried with android:state_focused it is working if focused it is giving yellow background now I want same thing to happen when it is filled.

This is the image here second box which is focused having yellow background and first box filled but not having yellow background I want filled box also should have yellow background

If focus state background color changing if filled then same should happen.

ppreetikaa
  • 1,149
  • 2
  • 15
  • 22
Deepak
  • 15
  • 7

3 Answers3

0

You can use OnTextChanged of edittext like below:

editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {     
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {

            if (editable.length()>0){
                //chnage the edittext background color if filled
            }else {
                //chnage the edittext background color if not filled
            }
        }
    });
Shahid Khan
  • 371
  • 2
  • 10
0

You can use TextWatcher to understand if your edittext is filled with text, then change its color if text length is > 0.

In kotlin:

yourEt.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                when (p0?.length) {
                    0 -> yourEt.setBackgroundColor(Color.parseColor("#FFFFFF"))
                    else -> yourEt.setBackgroundColor(Color.parseColor("#FFFFCB"))
                }

            }
        })

In java:

yourEt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {     
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {

            if (editable.length()>0){
                //chnage the edittext background color if filled
                yourEt.setBackgroundColor(Color.parseColor("#FFFFCB"))
            }else {
                //chnage the edittext background color if not filled
                yourEt.setBackgroundColor(Color.parseColor("#FFFFFF"))
            }
        }
    });
Nicola Gallazzi
  • 7,897
  • 6
  • 45
  • 64
-1

I don’t now how it works in android. But if you try to check on lostfocus if text box length > 0 then text box background color = yellow.