自定义属性中的可绘制资源

23

是否有可能从drawable文件夹中获取资源,并在某些自定义属性中进行编写,以便我可以编写:

<com.my.custom.View
    android:layout_height="50dp"
    android:layout_width="50dp"
    ...
    my_custom:drawableSomewhere="@drawable/some_image" />

然后在我的自定义视图类中,使用可绘制对象执行简单操作?

3个回答

64

实际上有一个称为 "reference" 的属性格式。因此,在您的自定义视图类中,您将会得到像这样的东西:

case R.styleable.PMRadiogroup_images:
                    icons = a.getDrawable (attr);
                    break;

假设您的attrs.xml中有类似以下内容:

<attr name="images" format="reference"/>

当您从视图构造函数中获取属性时,“a”是您从中获取的TypedArray。

这里有一个很好的类似答案:定义自定义属性


不要忘记添加正确的模式:xmlns:custom="http://schemas.android.com/apk/res-auto" - adalpari

10

看看 EdgarK 的答案吧,它更好。 (我不能删除它,因为它是被接受的答案)

这回答了你的问题吗?

"您可以使用 format="integer"、可绘制资源的资源 ID 和 AttributeSet.getDrawable(...)。"

(来自https://dev59.com/G3A75IYBdhLWcg3wFEwI#6108156


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

使用这些属性
<declare-styleable name="ExtendedFab">
    <attr name="fabText" format="string" />
    <attr name="fabIcon" format="reference" />
</declare-styleable>

这是布局

 <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" />

无法在Android 6设备上运行! - Kishan Solanki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接