虽然创建cutomView不是addView?

时间:2012-06-29 09:50:42

标签: android view add custom-component android-custom-view

我需要创建一个自定义视图,它扩展了RelativeLayout,只需要和imageView一样,与此customView的大小相同。

我的代码是:

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);
}   
}

在xml中,我创建了这个视图,如:

问题是我看不到buttonCoverImage?不知怎的,它还没有被创建,或被添加到myCustomView ......问题是什么?

1 个答案:

答案 0 :(得分:4)

如果你添加View by xml,那么android将实现构造函数

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

在你的情况下它是空的。我认为这是你的问题。