Tutorial How To Make A Toggle Button With Two Images

 

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.00 out of 5)
Loading...

 

 

Recently, I worked on a project where I had to make a custom toggle button. I found out a little trick that helped me get my work done with just a few lines of code. And here I am going to share with you that magic trick on How to make a toggle button with two images.

You just need to prepare two images/icons eg the following 2 images

Tutorial How To Make A Toggle Button With Two Images

 

Now we’re going to make a new project and name it as ToggleButtonExample.

Tutorial How To Make A Toggle Button With Two Images

 

Then, copy the above buttons and put them into the drawable folder.

Tutorial How To Make A Toggle Button With Two Images

 

Create a file and name it as “selector_toggle_button” and place it into the drawable folder too. Copy and paste the following code:

 

Later, we will assign this selector to an ImageView. Ic_toggle_on is going to be shown when the ImageView is in activated state, if not ic_toggle_off icon will take the place.

 

We will edit the main_activity.xml in layout folder by adding an ImageView to it. The important thing you need to remember is not to forget to assign selector_toggle_button to the ImageView. Here is how our xml file looks like:

 

The last thing we need to do to get our work done is edit our MainActivity to get the ImageView acts like a toggle button.

MainActivity

Now let’s run the program and see the result.

Tutorial How To Make A Toggle Button With Two Images

 

That’s all. With just a few lines of code and two images, you can get your own toggle button.

Hope you will find this post helpful.

 

Brought to you by RobustTechHouse team

 

 

Recommended Posts
Contact Us

We look forward to your messages. Please drop us a note for any enquiries and we'll get back to you, asap.

Not readable? Change text. captcha txt
Weird3Artificial Intelligence