Articles → Android → Change The Shape Of Button Based On Its State Using Selectors In Android

Change The Shape Of Button Based On Its State Using Selectors In Android






Example




  1. Create a button in layout file
  2. Picture showing the button inside the linear layout
    Click to Enlarge

  3. Add 2 shapes with the name myshape and myshape2


  4. <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <stroke android:color="#ff0000"></stroke>
        <gradient android:endColor="@color/design_default_color_primary"
           android:startColor="@color/colorPrimaryDark" android:angle="90"></gradient>
    </shape>




    <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
        <stroke android:color="@color/colorAccent"></stroke>
        <gradient android:endColor="@color/design_default_color_primary"
           android:startColor="@color/colorPrimaryDark" android:angle="90"></gradient>
    </shape>


  5. Add a selector (in the same way we have added a shape)
  6. <?xml version="1.0" encoding="utf-8"?>
    <selector
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" android:drawable="@drawable/myshape"></item>
        <item android:drawable="@drawable/myshape2"></item>
    </selector>


  7. Set the background of button to that of selector
  8. Picture showing setting the background of the button to the selector
    Click to Enlarge

Output




Picture showing the button in the default and the pressed state
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, November 28, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250