我需要创建一个自定义视图,它扩展了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... 可能是什么问题?