Android onClick method doesn't work on a custom view

后端 未结 10 1847
南旧
南旧 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:15

    You have to call setOnClickListener(this) in contructor(s) and implement View.OnClickListener on self.

    In this way:

    public class MyView extends View implements View.OnClickListener {
    
        public MyView(Context context) {
            super(context);
            setOnClickListener(this);
        }
    
        public MyView(Context context, AttributeSet attrs) {
            super(context, attrs);
            setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "On click.", Toast.LENGTH_SHORT).show();
        }
    }
    

提交回复
热议问题