Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Custom button OnClickListener is not getting invoked

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.

like image 943
Pria Avatar asked Aug 06 '10 09:08

Pria


2 Answers

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

like image 164
Tom Clabon Avatar answered Nov 09 '22 07:11

Tom Clabon


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.

like image 22
piotr_n Avatar answered Nov 09 '22 08:11

piotr_n