Reputation: 215
I want my button to appear to be depressed once the user removes finger from screen. I am using two images to simulate the bottom being pressed. Any help would be great
ImageButton imageButton;
boolean isPressed = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton =(ImageButton) findViewById(R.id.buttonID);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.sound);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isPressed) {
imageButton.setBackgroundResource(R.drawable.image);
}
else{
imageButton.setBackgroundResource(R.drawable.ispressed);
}
isPressed = !isPressed;
mediaPlayer.start();
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
});
}
}
Upvotes: 0
Views: 82
Reputation: 54224
This is a good candidate for using a "State list" drawable. You create a single drawable that has one image for the "pressed" state and another for the default state, and then you assign that to your button. You don't have to do any live-updating of the button background; it will just automatically transition between the two images for you.
<?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/ispressed"/>
<item android:drawable="@drawable/image"/>
</selector>
Now you just set your button background to this directly (either in Java or in XML):
imageButton =(ImageButton) findViewById(R.id.buttonID);
imageButton.setBackgroundResource(R.drawable.selector);
And then you don't have to do any updating in your OnClickListener
:
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isPressed = !isPressed;
mediaPlayer.start();
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
});
Upvotes: 1