我创建的简单小部件从ImageView扩展,在这个simle代码中我想将图像从布局xml设置为ImageView,我想要更改背景imageview图像并更改图像将其他图像设置为ImageView,但我的问题在第一次不要显示图像
1)我在attr.xml中创建了新属性:
<declare-styleable name="CIconButton">
<attr name="button_icon" format="integer" />
<attr name="background_icon" format="reference" />
</declare-styleable>
2)将CIconButton类用于布局:
<!-- xmlns:app="http://schemas.android.com/apk/res/com.sample.app.tpro" -->
<com.sample.widget.CIconButton
android:id="@+id/imgv_update_selected_phones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
app:button_icon="@drawable/icon_add_action" />
3)CIconButton
class
public class CIconButton extends ImageView implements OnClickListener {
private Drawable mSelectedBackground;
public CIconButton(Context context) {
super(context, null);
}
public CIconButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CIconButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CIconButton, defStyle, 0);
mSelectedBackground = a.getDrawable(R.styleable.CIconButton_button_icon);
setImageDrawable(mSelectedBackground);
a.recycle();
setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
问题:
我的自定义小部件类不会将图像集显示为布局xml,例如此类不显示来自drawable的icon_add_action
答案 0 :(得分:0)
我的问题解决了,我必须将第二个构造函数更改为:
public CIconButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
为:
public CIconButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
this
最后调用此类构造函数