Newbie question.
I am using an ImageView in my activity layout and would like similar behavior to a button. I notice that ImageView already generates onClick. What it doesn’t do is provide any visual feedback at touch and un-touch, which is what I’d like to add.
As well, I am going to need long-press handling; don’t yet know if ImageView does that.
I’ve dug in a bit and it I see that View implements Runnable; something is calling performClick when the user taps on the image, which then calls ImageView.PerformClick, which finally calls onClick for all the listeners (which is my activity). By the time ImageView handles PerformClick, it’s too late to change the image appearance; how do I do it at onShowPress time?
One more note: I’ve looked at (and tried) adding a gestureDetector to ImageView, but then it appears that I need to reimplement the onClick processing – at any rate, the activity stopped receiving onClick.
There may be a completely different way to do what I want and I’m open to hear about it.
Thanks.
Edit:
Test code for monitoring touch actions:
package com.example.mockup;
import android.content.Context;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
public class ImageGestureButton extends ImageButton
implements View.OnTouchListener, View.OnClickListener, View.OnDragListener,
View.OnLongClickListener
{
public ImageGestureButton (Context context, AttributeSet attrs)
{
super(context, attrs);
setOnTouchListener (this);
setOnClickListener (this);
setOnLongClickListener (this);
setOnDragListener (this);
setLongClickable (true);
}
public boolean onTouch (View v, MotionEvent e)
{
System.out.println ("onTouch " + e.getAction());
return false;
}
public void onClick (View v)
{
System.out.println ("onClick");
}
public boolean onDrag (View v, DragEvent e)
{
System.out.println ("onDrag");
return false;
}
public boolean onLongClick (View v)
{
System.out.println ("onLongClick");
return false;
}
}
I would use an ImageButton. Then use setOnClickListener() to wire up the method you want to be called when you click on it. In addition, you can use setOnLongClickListener() for the long press behavior.
Finally, you can also set different backgrounds, colors, etc. depending on the state (focused, selected, etc.). Take a look at the documentation.
As for the test code, your onLongClick() is returning false, which indicates that the long click wasn’t consumed. Try changing the return value to true and that should stop onClick() from also getting fired. Also, you’ll need to call the startDrag() method in order to fire the onDrag() event. See the android.view documentation for more info on the different event listeners and the startDrag() method.