问题描述
根据此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。这将在动画期间创建许多对象,但它们的生命周期很短。