Search code examples
javaandroidandroid-togglebutton

Change switch icon color from java code


I want to change the 'switch' icon color from java code and not from xml since the switch is created dynamically. Min SDK is 16. Help would be highly appreciated.

    Switch aSwitch = new Switch(context);
    holder.llSwitch.addView(aSwitch); 
    holder.navIcon.setText(context.getResources().getString(R.string.fa_bell_o));

Solution

  • You can check button is checkd or not and set the color with the state

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
    Switch mySwitch = new Switch(this);
    linearLayout.addView(mySwitch);
    mySwitch.setBackgroundColor(Color.BLACK);
    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
            if (isChecked)
                buttonView.setBackgroundColor(Color.RED);
            else buttonView.setBackgroundColor(Color.BLACK);
        }
    });
    

    Since you are messing up with Switch and ToggleButton check this answer Switch vs toggle

    Edit : Only for thumb color change you can try like below

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
    final Switch mySwitch = new Switch(this);
    linearLayout.addView(mySwitch);
    mySwitch.getThumbDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
            if (isChecked)
                mySwitch.getThumbDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
            else
                mySwitch.getThumbDrawable().setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY);
        }
    });