Reputation: 449
I'm trying to do a simple imageview with a colored background that when pressed change the color and at the end of the touch if it is outside the image area then it would return to the original color or else start another activity (like a button); so i decided to implement an onTouchListener in my activity using a kotlin lambda. This is the code:
imageview.setOnTouchListener{ view: View, event: MotionEvent ->
val rect = Rect(view.left, view.top, view.right, view.bottom)
when(event.action){
MotionEvent.ACTION_DOWN->{
view.setBackgroundColor(dark_color)
}
MotionEvent.ACTION_UP-> {
if (rect.contains(event.x.toInt(), event.y.toInt()))
startActivity(Intent(this, NewActivity::class.java)
else{
view.setBackgroundColor(normal_color)
}
}
}
true
}
And it works fine but while i was testing it i saw that the new activity was starting else if the touch is out of the image area, so i used the Log function to report the cordinates of the touch and i noticed that the cordinates (when MotionEvent.ACTION_UP was triggered) where different from the point that i was touching on the screen. Is it possible that the system is bugged ? (p.s. i tried also on the emulator and i had the same result and I can't use xml selectors)
Thanks for help!
Upvotes: 0
Views: 686
Reputation: 3869
The only thing you need to do is to create a selector. You set the selector as a background to your ImageView. So the selector manage the colour automatically (when the image is pressed or not). Then you set a listener on your ImageView to manage the click event. If the user moves his finger out of the ImageView area, the listener will NOT be triggered (it's automatically managed).
In your Java code
imageView.setOnClickListener(new View.OnClickListener {
public void onClick(...){
// Start the Activity
}
});
in your XML
<ImageView
android:background="@drawable/my_selector"
//...
my_selector.xml (must be in the drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/default_pressed" android:state_pressed="true" />
<item android:color="@color/default_not_pressed" />
</selector>
Upvotes: 1