R.K
R.K

Reputation: 1839

how to add a rounded rectangular toggle_switch in android?

I need to make a rounded rectangular toggle_switch in android like the one given below:

enter image description here

Can anyone guide me the complete steps to do so.

Upvotes: 3

Views: 6646

Answers (2)

R.K
R.K

Reputation: 1839

I solved my problem as follow :

Added a toggle button to my xml layout file :

<ToggleButton
                android:id="@+id/ToggleButton1"
                android:layout_width="120dp"
                android:layout_height="25dp"
                android:layout_marginRight="30dp"
                android:layout_weight="2"
                android:background="@drawable/toogle_switch"
                android:text="ToggleButton"
                android:textOff=""
                android:textOn="" />

Then defined a custom togglebutton Background "toogle_switch" in 'drawable' folder as below:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/switchon" android:state_checked="true"></item>
    <item android:drawable="@drawable/switchoff" android:state_checked="false"></item>

</selector>

switchon & switchoff are the 2 images I have shown in question.

Hope it helps everyone.! :)

Upvotes: 3

ezaquarii
ezaquarii

Reputation: 1916

Here you go:

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

Exact image shown is determined by so called 'selector' or 'state list', which is a piece of XML that maps button states to images.

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

You need to:

  1. prepare images for all possible states of the button (toggled, pressed, etc) and place them in drawable folders
  2. write a state list (selector) that binds images with button states
  3. connect this state list to button android:background property

Upvotes: 0

Related Questions