I've created a basic custom Switch
, as defined below.
<Switch
android:id="@+id/availSwitch"
android:layout_width="wrap_content"
android:switchMinWidth="110dp"
android:layout_height="wrap_content"
android:track="@drawable/switch_track"
android:thumb="@drawable/thumb"/>
The @drawable/thumb
is a simple PNG which works fine.
The @drawable/switch_track
is defined below. @drawable/trackon
and @drawable/trackoff
are PNG's.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/trackoff" />
<item android:state_checked="true" android:drawable="@drawable/trackon" />
<item android:drawable="@drawable/trackoff" />
</selector>
This switch looks and works as intended for the most part, but is there some way to 'animate' the track as the thumb travels over it on user drag? Either fade between checked and unchecked, or preferably change 'behind' the thumb.
The current behaviour is shown below.
Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as “anim”. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file.
All you need to do is set an attribute in the layout to tell the Android system to animate these layout changes, and system-default animations are carried out for you. Tip: If you want to supply custom layout animations, create a LayoutTransition object and supply it to the layout with the setLayoutTransition() method.
Easiest solution: set android:animateLayoutChanges="true" on the container holding your views. To put it into some context: If you have a layout like below, all visibility changes to the views in this container will be animated automatically. This animates the alpha, not the position.
There was a time I was also looking for the same when I needed a toggle button functionality similar to native iOS which can be dragged to on/off for one of my projects. At that time I searched hard and I found this library.
https://github.com/pellucide/Android-Switch-Demo-pre-4.0
So hope this is what you are looking for too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With