Violet Giraffe
Violet Giraffe

Reputation: 33579

Android: how to switch button's pressed state programmatically?

I have a button with 2 distinct pictures for pressed and released state. How do I switch the state programmatically?

Upvotes: 12

Views: 10030

Answers (2)

Deepanshu
Deepanshu

Reputation: 163

this can be done by using custom drawable backgound inside our ImageButton

buttonSelector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item  android:drawable="@drawable/button_pressed" android:state_selected="true"/>
<item android:drawable="@drawable/button_pressed" android:state_focused="true" />
<item android:drawable="@drawable/button_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/button_disabled" android:state_enabled="false" />
<item android:drawable="@drawable/button_default" />

put this @drawable/buttonSelector.xml code inside the background of your Image Button xml code

<ImageButton
   android:id="@+id/demoBtn"
   android:background="@drawable/buttonSelector"
   android:layout_width="70dp"
   android:layout_height="70dp"
   android:src="@drawable/btndefaultImage"/>

In your Mainactivity you can set button state as pressed or in default state by using below line

demoBtn.setSelected(true);//used to maintain button as selected/pressed
demoBtn.setSelected(false);//used to maintain button as unseleced/default

Upvotes: 1

Jason Robinson
Jason Robinson

Reputation: 31283

View.setPressed(boolean)

Upvotes: 36

Related Questions