Android onClick method doesn't work on a custom view

后端 未结 10 1896
南旧
南旧 2021-01-01 09:32

I\'ve started working on an app. I build the menu yesterday but the onClick method doesn\'t work! I created a class that extends View and called her MainMenuObject - that cl

10条回答
  •  情话喂你
    2021-01-01 10:23

    I just had the same Problem - I created a custom view and when I registered a new Listener for it in the activity by calling v.setOnClickListener(new OnClickListener() {...}); the listener just did not get called.

    In my custom view I also overwrote the public boolean onTouchEvent(MotionEvent event) {...} method. The problem was that I did not call the method of the View class - super.onTouchEvent(event). That solved the problem. So if you are wondering why your listener does not get called you have probably forgotten to call the superclass'es onTouchEvent method

    Here is a simple example:

    private static class CustomView extends View implements View.OnClickListener {
        public CustomView(Context context) {
            super(context);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            super.onTouchEvent(event);   // this super call is important !!!
            // YOUR LOGIC HERE
            return true;
        }
    
        @Override
        public void onClick(View v) {
            // DO SOMETHING HERE
        }
    }
    

提交回复
热议问题