我在Android中实现了一个定制的“启用”按钮。当我的按钮被禁用时,我将android:stateListAnimator=设置为“@null”,并希望在启用时将其重置为默认的Widget.AppCompat.Button样式。但我怎么能重设它呢?我要设置什么stateListAnimator?
发布于 2021-12-27 17:50:15
如果我们查看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。然后,您可以捕获代码中的值,保存它,并在代码中将动画设置为null。然后,可以在需要时替换捕获状态列表动画器值。
https://stackoverflow.com/questions/70490216
复制相似问题