0

I am new to android and trying out some functions. I have an xml file that is called upon a button click:

<?xml version="1.0" encoding="utf-8"?>


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/button_pressed"/>
<item android:state_pressed="true" android:drawable="@drawable/button_pressed" />
<item android:drawable="@drawable/btn_not_pressed" />  
</selector>

How do I edit this code so that when a button is pressed it remains in that state until it is clicked again, when it reverts back to the previous state?

3 Answers3

1

You should combine ToggleButton with checked background as described in existing answer

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>
Community
  • 1
  • 1
alexei burmistrov
  • 1,417
  • 10
  • 13
0

If you choose to do it programmatically, you can do it like this,

boolean flag = true;

Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
            if(flag){
                 button.setBackgroundResource(R.drawable.clickedonce);
                 flag = false;
            }else{
                 button.setBackgroundResource(R.drawable.clickedtwice);
                 flag = true;
           }
         }
     });

Maybe it helps.

Oam
  • 912
  • 6
  • 7
0

try fixing it in your java class. Add a flag for when button is selected and when it is not and then when it's selected or the window is open add image for pressed state and when it is closed add image for when it is not pressed.