有没有办法为 MaterialButton 的 iconTint 设置 MotionLayout 自定义属性?

问题描述

根据此article

CustomAttribute 使用 attributeName 指定,它需要匹配对象的 getter/setter 方法,以便: getter:getName(例如 getBackgroundColor) setter: setName (e.g. setBackgroundColor)

(所以 motion:attributeName 必须是 backgroundColor

我尝试过使用材质按钮使用波纹管属性名称,但没有一个起作用。

<CustomAttribute motion:attributeName="IconTintResource" motion:customColorValue="@color/keyTextColor" />

'IconTintResource','iconTintResource','IconTint','iconTint','ColorFilter'

有什么建议吗?

这些是我遇到的错误

E/TransitionLayout: Custom Attribute "IconTint" not found on com.google.android.material.button.MaterialButton

E/TransitionLayout: com.google.android.material.button.MaterialButton must have a method setIconTint

E/TransitionLayout: no method setIconTinton View "f_editor_image_view_terminal"

解决方法

MotionLayout 的 CustomAttribute 使用反射来设置视图上的值(大致基于 Java bean 约定)

所以如果你说

<CustomAttribute motion:attributeName="foo" motion:customColorValue="@color/keyTextColor" />

它寻找一个方法 setFoo(int value); 不幸的是,即使 MaterialButton 解析 xml android:iconTint="#FFF" 它没有方法 setIconTint(int color);

MotionLayout 还将检查 setFoo(Drawable()) 并使用 ColorDrawable

可以创建 MaterialButton 的子类并实现需要的方法 setInconTint(int color)

class MyButton extends MaterialButton {

    public MyButton(@NonNull Context context) {
        super(context);
    }

    public MyButton(@NonNull Context context,@Nullable AttributeSet attrs) {
        super(context,attrs);
    }

    public MyButton(@NonNull Context context,@Nullable AttributeSet attrs,int defStyleAttr) {
        super(context,attrs,defStyleAttr);
    }

    void setIconTint(int color) {
        ColorStateList colorStateList = new ColorStateList(new int[1][0],new int[]{color});
        setIconTint(colorStateList);
    }
}

这将适用于 MotionLayout。这将在动画期间创建许多对象,但它们的生命周期很短。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...