Reputation: 14112
In Mono For Android, I have an ImageButton and I want to change its image while user is holding the button. And when user release the button image should change to pervious image. I am trying with the code below but nothing happens:
private void _goForward_KeyPress(object sender, View.KeyEventArgs e)
{
if(e.Event.Action == KeyEventActions.Down)
{
_goForward.SetImageResource(Resource.Drawable.arrowUpGreen);
//Then do some stuff
}
else
{
_goForward.SetImageResource(Resource.Drawable.arrowUpRed);
//Then do some stuff
}
}
I am not sure if I am doing this with the right event. What event usualy should be used in this case?
Upvotes: 1
Views: 2158
Reputation: 10139
You need to attach your method to the button's KeyPress
event for it to be called, since the wiring doesn't happen automatically:
_goForward.KeyPress += _goForward_KeyPress;
EDIT
Oops, I should have read the question a little more closely the first time. Since you're trying to hook into when the button is touched, you want the Touch
event instead:
_goForward.Touch += _goForward_Touch;
and
private void _goForward_Touch(object sender, View.TouchEventArgs touchEventArgs)
{
if (touchEventArgs.Event.Action == MotionEventActions.Down)
{
Toast.MakeText(this, "down", ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "up", ToastLength.Short).Show();
}
}
Upvotes: 1
Reputation: 6604
Try this:
Use the selector for this
Say its name as: background_drawable.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/YOUR_IMAGE_WHEN_PRESSED"
android:state_pressed="true" />
<item
android:drawable="@drawable/YOUR_IMAGE_WHEN_FOCUSED"
android:state_focused="true" />
<item
android:drawable="@drawable/YOUR_IMAGE_WHEN_NOT_ENABLED"
android:state_enabled="false"
/>
<item
android:drawable="@drawable/DEFAULT_IMAGE_WHICH_YOU_WANT_ALWAYS" />
</selector>
And in you main.xml file
<ImageButton
android:background="@drawable/background_drawable"/>
Upvotes: 5