简体   繁体   中英

Retain color of Switch when disabeld

I am using a Switch in xamarin forms. When I toggle, the color is Pink when true and grey when false.

When I disable the switch as I do not want the user to toggle. then the color change to Grey.

How can i retain the color of the Switch. When it is disable and it is true it should be in default color but not grey,

Could you please suggest how can i achieve this.

<Switch IsToggled="True" IsEnabled="False"/>

Thanks Rao

I have investigated a bit this problem and I can see two solutions:

Easy way

Use a private boolean variable instead of using the IsEnabled property. Then when the clicked event is handled, check the switch's status with the variable.

Hard way

Overwrite the Switch control to get this behaviour. You can follow this guide .

As seen from the Switch for Xamarin.Forms , there is currently no option of specifying the color. Conclusively, you will have to create your own renderer for both iOS and Android .

Android

Essentially, what you need to do is to override the OnElementChanged and OnCheckChanged events and check for the Checked Property of the Control . Afterwards, you can set the ThumbDrawable of the Control and execute SetColorFilter with the color you want to apply. Doing so although requires Android 5.1+. An example is given here .

You could also create utilise the StateListDrawable and add new ColorDrawables for the StateChecked , StateEnabled and lastly, a default value as well. This is supported for Android 4.1+. An example of using the StateListDrawable is provided in detail here .

iOS

iOS is somewhat more simple. Simply create your own SwitchRenderer , override the OnElementChanged event and set the OnTintColor and ThumbTintColor .

I hope this helps.

You need to make custom renderer for your control in this case switch like that and set color when it changes:

class CustomSwitchRenderer : SwitchRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)
    {
        base.OnElementChanged(e);

        this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
        this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);

        this.Control.CheckedChange += this.OnCheckedChange;
    }

    private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
    {
        this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
        this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM