【问题标题】:Android simple widget to show image into ImageView将图像显示到 ImageView 中的 Android 简单小部件
【发布时间】:2015-02-24 09:47:44
【问题描述】:

我创建了从 ImageView 扩展的简单小部件,在这个简单的代码中,我想将图像从布局 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

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

【问题讨论】:

  • 如果你扩展ImageView,为什么不直接使用android:src属性,让super构造函数负责加载图像?
  • @Mike M. 获取CIconButton class中的变量attr
  • 对不起,我不明白你的意思。
  • @Mahdi.Pishguy 。你应该使用 android:src 来显示你的图标,因为你正在扩展 Imageview
  • @Ramesh 那篇文章与这个问题无关。

标签: android android-widget


【解决方案1】:

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

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

到:

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

this最后调用这个类的构造函数

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多