16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CustomViewのOnClickが反応しない時の対処方法

Posted at

カスタムビューを作成してOnClickListenerをセットしたのにタップしても反応しない時の対処方法です。

#問題の現象

例えばこんな感じのカスタムビューを作った時。

custom_button.java
public class CustomButton extends RelativeLayout {

    private OnClickListener listener;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 略
    }

    // 略
}

OnClickListenerをセットしても反応しません。

mCustomButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.d(TAG, "clicked");
    }
});

#対処方法

OnClickイベントをカスタムビュー自身でハンドリングしてあげると反応するようになります。

custom_button.java
public class CustomButton extends RelativeLayout {

    private OnClickListener listener;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 略
    }

    // 略

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (listener != null) listener.onClick(this);
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP
                && (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER
                || event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            if (listener != null) listener.onClick(this);
        }
        return super.dispatchKeyEvent(event);
    }

    public void setOnClickListener(OnClickListener listener) {
        this.listener = listener;
    }

}
16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?