自定义属性的可绘制资源

Pro*_*res 11 xml android drawable

有没有可能在一些自定义属性中从drawable文件夹中获取资源,所以我可以写:

<com.my.custom.View
    android:layout_height="50dp"
    android:layout_width="50dp"
    ...
    my_custom:drawableSomewhere="@drawable/some_image" />
Run Code Online (Sandbox Code Playgroud)

然后在我的自定义视图类中使用drawable简单执行操作?

Edg*_*arK 46

实际上有一种称为"引用"的属性格式.因此,您将在自定义视图类中获得类似的内容:

case R.styleable.PMRadiogroup_images:
                    icons = a.getDrawable (attr);
                    break;
Run Code Online (Sandbox Code Playgroud)

虽然你的attrs.xml中有这样的东西:

<attr name="images" format="reference"/>
Run Code Online (Sandbox Code Playgroud)

其中"a"是您从视图构造函数中获取的属性获得的TypedArray.

这里有一个很好的类似答案:定义定制的attrs


loe*_*chg 8

见EdgarK的答案; 它更好.(我不能删除它,因为这是接受的答案)

这回答了你的问题了吗?

"你可以使用format ="integer",drawable的资源id和AttributeSet.getDrawable(...)."

(来自/sf/answers/427570951/)


Jua*_*ron 7

我用过这个,它适用于 kotlin(编辑以粘贴完整的类)

class ExtendedFab(context: Context, attrs: AttributeSet?) :
LinearLayout(context, attrs) {

init {

    LayoutInflater.from(context).inflate(R.layout.component_extended_fab, this, true)
    attrs?.let {

        val styledAttributes = context.obtainStyledAttributes(it, R.styleable.ExtendedFab, 0, 0)
        val textValue = styledAttributes.getString(R.styleable.ExtendedFab_fabText)
        val fabIcon = styledAttributes.getDrawable(R.styleable.ExtendedFab_fabIcon)

        setText(textValue)
        setIcon(fabIcon)
        styledAttributes.recycle()
    }
}

/**
 * Sets a string in the button
 * @param[text] label
 */
fun setText(text: String?) {
    tvFabLabel.text = text
}

/**
 * Sets an icon in the button
 * @param[icon] drawable resource
 */
fun setIcon(icon: Drawable?) {
    ivFabIcon.setImageDrawable(icon)
}
}
Run Code Online (Sandbox Code Playgroud)

使用此属性

<declare-styleable name="ExtendedFab">
    <attr name="fabText" format="string" />
    <attr name="fabIcon" format="reference" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

这是布局

 <com.your.package.components.fab.ExtendedFab
        android:id="@+id/efMyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:elevation="3dp"
        android:clickable="true"
        android:focusable="true"
        app:fabIcon="@drawable/ic_your_icon"
        app:fabText="Your label here" />
Run Code Online (Sandbox Code Playgroud)