问题
I have a custom button, on which I am capturing its onTouchEvent.
public class CustomNumber extends ToggleButton {
boolean drawGlow = false;
float glowX = 0;
float glowY = 0;
float radius = 30;
public CustomNumber(Context context) {
super(context);
}
public CustomNumber(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomNumber(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
Paint paint = new Paint();
{
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setAlpha(70);
};
@Override
public void draw(Canvas canvas){
super.draw(canvas);
if(drawGlow)
canvas.drawCircle(glowX, glowY, radius, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction() == MotionEvent.ACTION_DOWN){
drawGlow = true;
}else if(event.getAction() == MotionEvent.ACTION_UP)
drawGlow = false;
}
glowX = event.getX();
glowY = event.getY();
this.invalidate();
return true;
}
This custom button is the part of a grid. When I am adding this button to the grid, I have set an OnClickListener to it. But, the code in the OnClickListener is never invoked.
GridAdapter code, where I am adding the button with listener:
public View getView(final int position, final View convertView, final ViewGroup parent) {
CustomNumber tBtn;
if (convertView == null) {
tBtn = new CustomNumber(context);
tBtn.setTextOff("");
tBtn.setTextOn("");
tBtn.setChecked(false);
tBtn.setId(position);
tBtn.setOnClickListener(tBtnListener);
tBtn.setLayoutParams(new GridView.LayoutParams(35, 35));
} else {
tBtn = (CustomNumber) convertView;
}
return tBtn;
}
Please help.
回答1:
In your onTouchEvent implementation, instead of "return true;", do...
return super.onTouchEvent(event);
You're overriding the superclass' implementation which is what is responsible for calling the listener. By calling the superclass' implementation it should act as it did before. This is why your code works when you comment out the method - because you're no longer overriding the superclass' implementation
回答2:
Try impelementing OnTouchListener in your activity (instead of onClickListener) and change onClick() to onTouch(). This worked for me. Both onTouchEvent from my custom view and onTouch() from Activity are being called. Remeber to return "false" in onTouch() and "true" in OnTouchEvent of your custom view.
回答3:
I guess Mathias's comment is correct, you have to return false in your onTouchEvent method when you want the onClick() event listener to be triggered instead of a subsequent onTouch() event listener.
You can find more precision int UI Events documentation
回答4:
Can you just execute your code in OnTouchEvent (a click is MotionEvent.ACTION_DOWN as you already know)?
来源:https://stackoverflow.com/questions/3422358/android-custom-button-onclicklistener-is-not-getting-invoked