Programatically changing one EditText color change

2019-07-14 00:40发布

问题:

I have very strange problem in Android 5. If user inputs something wrong I want to set error to edittext and change it color to red, and when user starts typing something I want to change color back to green. This is how i do it:

eText.setError(message);
    eText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
    eText.addTextChangedListener(new TextWatcher() {


        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            eText.getBackground().setColorFilter(
                    ctx.getResources().getColor(R.color.dark_green), PorterDuff.Mode.SRC_ATOP);
        }

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

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

In lower android versions than 5, everything works perfect, but not in Lollipop. If I change one edittext color, all edittexts in all app changes it color. Is there any way to fix this strange thing? Or it is some of material design and Android 5 tricks which I don't know?

回答1:

The problem is that the background Drawable is reused across many Views. To ensure the Drawable is not shared between multiple Views you should use the mutate method.

See: mutate()

Example code:

Drawable background = mainMenuButton.getBackground();
background.mutate();
background.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.light_green), PorterDuff.Mode.MULTIPLY));
mainMenuButton.setBackground(background);

Android 5.0 Lollipop: setColorFilter "leaks" onto other buttons



回答2:

Do Same for like spinner colour changes..

In Android Lollipop Version you have to implement code for kitkat version and lollipop version separately , please do this code for change background of spinner. its example of image background changes of images.

      if (Build.VERSION.SDK_INT => Build.VERSION_CODES.KitKat) 
                        {
                            //for Lollipop Vession
                      // do on textChangeListner code
eText.setBackgroundDrawable(Color.RED);
                        }
                        else
                        {
     // do on textChangeListner code
eText.setBackgroundResource(Color.RED);
                        }

i hope it helps you, if it is useful code for then please mark me .. Thanx.. :)