Android 将图像显示到 ImageView 中的简单小部件

Android simple widget to show image into ImageView

我创建了从 ImageView 扩展的简单小部件,在这个简单的代码中,我想将图像从布局设置到 ImageView xml,我想更改背景图像视图图像并更改图像以将其他图像设置到 ImageView,但我的问题是第一次不显示图像

1) 我正在为 attr.xml:

创建新属性
<declare-styleable name="CIconButton">
    <attr name="button_icon"     format="integer" />
    <attr name="background_icon" format="reference" />
</declare-styleable>

2) 使用 CIconButton class 布局:

<!-- 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) {
    }
}

问题:

我的自定义小部件 class 不显示设置到布局中的图像 xml,例如这个 class 不显示 icon_add_action 来自 drawable

我的问题已解决,我必须将第二个构造函数更改为:

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

至:

public CIconButton(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

this 最后调用这个 class constrctor