Reputation: 59
I have prepared a two graphics for background of my button. I have one put in "android:background" in xml file and I have no idea how to make to change this image for another image for a while after click.
I tried to do this using OnHoverListener and OnClickListener but it doesn't work
Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Button.setBackground(getResources().getDrawable(
R.drawable.img_hovered));
Button.setBackground(getResources().getDrawable(R.drawable.img));
}
});
Upvotes: 0
Views: 763
Reputation: 2059
if you want to make it clickable button, then make a selector xml in drawable folder and copy below code.
lets take its name as app_click.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/yourimage_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/yourimage_unpressed"/>
</selector>
then use this selector for your button Selector
.
like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/app_click" />
Upvotes: 1
Reputation: 51571
See if the following does what you are looking for. The code assumes that R.drawable.img
is the original background. When Button
is clicked, the background changes to R.drawable.img_hovered
for 0.5 seconds. Then it reverts back to R.drawable.img
:
Button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Button.setBackground(getResources().getDrawable(
R.drawable.img_hovered));
new Handler().postDelayed(new Runnable() {
public void run() {
Button.setBackground(getResources().getDrawable(R.drawable.img));
// Button Click Code Here
}
}, 500L); // 0.5 Seconds
}
});
Upvotes: 1