如果我们查看AppcompatButton.java,我们会看到默认按钮样式是由buttonStyle 属性定义的:
public AppCompatButton(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.buttonStyle);
}
现在我们知道了这一点,我们可以从主题中提取状态列表动画师,如下所示:
// Find the button style used in the theme.
val a = theme.obtainStyledAttributes(
intArrayOf(android.R.attr.buttonStyle)
)
val buttonStyle = a.getResourceId(0, -1)
a.recycle()
// From the button style, get the state list animator that is defined.
val ta =
theme.obtainStyledAttributes(buttonStyle, intArrayOf(android.R.attr.stateListAnimator))
val id = ta.getResourceId(0, -1)
// If we have found a state list animator, set it to the button. "binding.b1" is the button.
if (id != -1) {
val stateListAnimator = AnimatorInflater.loadStateListAnimator(this, id)
binding.b1.stateListAnimator = stateListAnimator
}
也可以通过不将其设置为@null 来让按钮默认为状态列表动画器。然后,您可以在代码中捕获该值,将其保存并在代码中将 animator 设置为 null。然后,您可以根据需要替换捕获状态列表动画器值。