how to alternate background and textcolor of a button in android studio?

Viewed 55

i would like to aternate background and textcolor attributes when user touches a button. in details i would like the user touches the button, then background and text colors changes and when the user touches again the button features combe back to the initial values. this is my code:

  fees.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
SharedPreferences.Editor editor=sharedPref.edit();
            editor.putBoolean("feesIn",!feesIn);
            editor.apply();
            if(sharedPref.getBoolean("feesIn",false)){
                fees.setBackgroundColor(Color.parseColor("#515de1"));
                fees.setTextColor(Color.WHITE);
            }else{
                fees.setBackgroundColor(Color.WHITE);
                fees.setTextColor(Color.parseColor("#515de1"));
            }

            return false;
        }


    });

when i touch the first time, button features changes like i wish but the second time nothing happen.

1 Answers

Try out this, just change boolean variable when it hits. Try this and let me know if it worked.

 fees.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event) {

        if(sharedPref.getBoolean("feesIn",false)){
            fees.setBackgroundColor(Color.parseColor("#515de1"));
            fees.setTextColor(Color.WHITE);
            sharedPref.setBoolean("feesIn",true);

        }else{
            fees.setBackgroundColor(Color.WHITE);
            fees.setTextColor(Color.parseColor("#515de1"));
            sharedPref.setBoolean("feesIn",false);

        }

        return false;
    }


});
Related