cannot SetBackground Resource image for android buttons -


i want button 2 states:

  1. off
  2. on(or click).

i have set normal image in button background , trying change image(pressed) onclick method, doesn't change.

final button button1 = (button) findviewbyid(r.id.button1);  button1.setonclicklistener(new onclicklistener() {  private int flag;  @override public void onclick(view v) {     if(flag==1)     {       button1.setbackgroundresource(r.drawable.on);           flag=0;     }     if(flag==0)     {           button1.setbackgroundresource(r.drawable.off);           flag=1;     }  } }); 

there option: can use android.widget.togglebutton selectors:

code:

togglebutton togglebutton = (togglebutton) view.findviewbyid(r.id.togglebutton); togglebutton.setchecked(true/false); 

main layout snippet:

.... <togglebutton android:id="@+id/togglebutton"               android:layout_width="wrap_content"               android:layout_height="wrap_content"               android:texton=""               android:textoff=""               android:background="@drawable/toggle_states"/> .... 

res/drawable/toggle_states.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">     <item android:state_checked="true" android:drawable="@drawable/icon_alarm_on"></item>     <item android:state_checked="false" android:drawable="@drawable/icon_alarm_off"></item> </selector> 

android set drawable/icon_alarm_on or drawable/icon_alarm_off automatically depending on state set togglebutton.setchecked() method


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -