Search code examples
androidandroid-studioandroid-buttonandroid-library

Set onClickListener in an Android custom view


I am trying build simple library for button, inside library folder I created below class

 public class SimpleImageButton extends AppCompatImageView implements AppCompatImageView.OnClickListener{

    public Context mContext;
    Activity activity;

    public SimpleImageButton (Context context) {
        super(context);
        mContext = context;
        setCustomTypeface(context, null);

    }

    public SimpleImageButton (Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setCustomTypeface(context, attrs);

    }

    public SimpleImageButton (Context context, AttributeSet attrs, int defStyleAttr) 
    {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setCustomTypeface(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setCustomTypeface(Context context, AttributeSet attrs)  {
        if(isInEditMode())
            return;
        TypedArray a = context.obtainStyledAttributes(attrs, 
        android.support.v7.appcompat.R.styleable.TextAppearance);
        setBackground(ContextCompat.getDrawable(mContext, 
    R.drawable.applogo_ads));
        a.recycle();

    }
   public void onClick(View view) {
        // here i have some functions to execute
    }
}

and my Mainclass in App folder

   SimpleImageButton imgBtn= (SimpleImageButton )findViewById(R.id.clickButton);

imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               imgBtn.onClick(view);
              // without this line how can i reach to onclick() of simpleImageButton class
            }
        });

so it is woking fine when i click button. but i want to make library button to work directly, without onClick function inside main activity, on clicking button should directly redirect to SimpleImageButton class onclcik method

I am very new to stack overflow , if any mistakes in the grammar / way of asking question please never mind. thank you.


Solution

  • Use setOnClickListener(this) inside your view's constructor.

    public SimpleImageButton (Context context) {
            super(context);
            mContext = context;
            setCustomTypeface(context, null);
            setOnClickListener(this);
        }