Search code examples
androidandroid-studioimagebutton

How to change the image of an ImageButton when clicked


I am trying to make a media player with the play button and when ever the play button is clicked it changes to the pause button. The code I have is below but whenever I click the play button the button disappear and nothing happens.

public class MainActivity extends Activity {
 boolean isPressed = false;
 private ImageButton btnTest;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnTest =(ImageButton) findViewById(R.id.imageButton2);
    btnTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(isPressed)
                btnTest.setBackgroundResource(R.drawable.img2);
            else
                btnTest.setBackgroundResource(R.drawable.img3);

            isPressed = !isPressed;
        }

    });

} 

I want the image to toggle between play and paused every time it is clicked. What should I do to get this behavior?


Solution

  • try setImageResource(int Res_id) in place of setBackgroundResource. Tell me if it worked.