Search code examples
androidviewadditioncustom-componentandroid-custom-view

while creating a cutomView doesn't addView?


I need to create a custom view, which extends RelativeLayout and simply needs to have and imageView as in the same size of this customView.

My code is:

public class MyCustomButton extends RelativeLayout {

ImageView buttonCoverImage;

public MyCustomButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public MyCustomButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyCustomButton(Context context) {
    super(context);

    setClickable(true);
    setFocusable(true);
    setEnabled(true);

    buttonCoverImage = new ImageView(getContext());

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    setLayoutParams(lp);

    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    buttonCoverImage.setLayoutParams(new RelativeLayout.LayoutParams(100, 100));

    buttonCoverImage.setBackgroundResource(R.drawable.button_selector);
    buttonCoverImage.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            performClick();
        }
    });

    this.addView(buttonCoverImage);
}   
}

And in xml, i created this view like:

The problem is i can't see the buttonCoverImage? Somehow it's not been created, or added to myCustomView... What could the problem be?


Solution

  • If you add View by xml, then android will implement constructor

    public MyCustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    

    And in your case it's empty. I think it's your problem.