I have been trying to create a customized toggle button in native android, But I’m not able to achieve it. Here is the Image which I want to look like :
If you need to create a custom switch, you don’t have to create a custom view. In fact, with the help of some drawables you will be able to achieve what you want.
I will give an example and you can customize it to your needs.
There are three main resources that you need.
Thumb
Track
Text Coloring.
Let’s start with the Thumb which represents the moving part in the Switch.
We need to create a style for this text because it can’t be added directly to the Switch.
So, in your styles.xml create a new style for the text color.
To achieve this you can use a TabLayout inside a MaterialCardView. The MaterialCardView is needed to draw the corner radius for the outer section. In the TabLayout you can use the app:tabBackground to set a Drawable Selector for the Tab selected/unselected state and the app:tabTextAppearance where you can set a custom font style or size for the Tab.
3
Answers
Key classes are the following:
ToggleButton
Switch
SwitchCompat
CompoundButton
You can even use Slider. Init the thumb and the track.
If you need to create a custom
switch
, you don’t have to create a custom view. In fact, with the help of some drawables you will be able to achieve what you want.I will give an example and you can customize it to your needs.
There are three main resources that you need.
Let’s start with the
Thumb
which represents the moving part in theSwitch
.thumb_selector.xml
Then we need to draw the track which represents the bottom layer of the
Switch
.track_selector.xml
Now moving to the last part which is the text coloring to give our text a different color depending on the selection state.
text_color_selector.xml
We need to create a style for this text because it can’t be added directly to the
Switch
.So, in your
styles.xml
create a new style for the text color.styles.xml
Finally, we need to tie all parts together in our layout.
layout.xml
Results
To achieve this you can use a
TabLayout
inside aMaterialCardView
. TheMaterialCardView
is needed to draw the corner radius for the outer section. In theTabLayout
you can use theapp:tabBackground
to set a Drawable Selector for the Tab selected/unselected state and theapp:tabTextAppearance
where you can set a custom font style or size for the Tab.Xml Layout:
where
@drawable/tabs_selector
is a drawable Selector to set the Tab Selected/Unselected state like below:and
@style/CustomTabTextAppearance
is a Custom Tab Text Appearance in case you want to change the Tab size or Font Family like below:Result: