Android button onclick override

后端 未结 3 1910
面向向阳花
面向向阳花 2020-12-10 03:24

I would like to create a CustomButton which has a predefined onClick. In fact, my object would do the same job than

CustomButton mB         


        
相关标签:
3条回答
  • 2020-12-10 03:52

    You were really close:

    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class CustomButton extends Button implements OnClickListener{
    
        public CustomButton(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        public CustomButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public CustomButton(Context context) {
            super(context);
            init();
        }
    
        private void init(){
            setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            // Do something
        }
    
    }
    
    0 讨论(0)
  • 2020-12-10 03:55

    Use that code:

    class CustomButton extends Button implements View.OnClickListener{
         CustomButton(Context c, AttributeSet attrs) {
             ...
             setOnClickListener(this);
             ...
         }
    
        @override
        public void onClick(View v){
            //add your code here
        }
    }
    
    0 讨论(0)
  • 2020-12-10 03:57

    In your button class just implement:

    @Override
    public void onClick(View v) {
        showSomething();
    }
    

    Or if you want more granular control:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        showSomething();
    }
    

    You can either implement your click logic in the method by checking the event.getAction(), or send it to a GestureDetector to figure out when a click has been performed.

    0 讨论(0)
提交回复
热议问题