开发者

Android: Changing Image When Tapped Then Reverting Back

开发者 https://www.devze.com 2023-03-28 00:32 出处:网络
I have an image but am wondering how I can have this image change to another one when the users finger is in contact with the screen and then revert back to the old image when they 开发者_如何学JAVAta

I have an image but am wondering how I can have this image change to another one when the users finger is in contact with the screen and then revert back to the old image when they 开发者_如何学JAVAtake their finger away.

I'm eager to learn this and have tried an on click listener method but I could only really make the image change permanently and even then it worked poorly. So could someone help me out with this please?


Yes that should work with a State List which is a kind of Drawable, for which you can define different other drawables for different states (among which "pressed", "focused", selected", etc.) :

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

Note that the order of the items is important and that your default drawable should be placed last in the selector item list. Ex :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable_resource_pressed" android:state_pressed="true">
    <item android:drawable="@drawable_resource_regular">
</selector>


What you need here is an OnTouchListener. Register it to the view that you want touched when the image should change (e.g. the ImageView that holds the image itself) via setOnTouchListener().

That listener has a callback onTouch that supplies you with a MotionEvent. Use MotionEvent.getAction() and test if it equals MotionEvent.ACTION_DOWN or MotionEvent.ACTION_UP. Those are the corresponding events when the user presses the view (down) or releases the press (up). Just react accordingly there and set the image to your ImageView.

Edit: And the statelist mentioned in the other post works too, and is probably there more elegant solution here (since it does all this here for you in the background) when you want to change the image by touching it.

This is still useful to know, you will need it sooner or later somewhere else. For example when you want to change the image by pressing another view and not the image itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号