I implemented a costumized "enabled" button in Android. I set android:stateListAnimator="@null" when my button is disabled and want to reset it to the default Widget.AppCompat.Button style, when it is enabled. But how can I reset it? What do I have to set stateListAnimator ?
Asked
Active
Viewed 310 times
1 Answers
1
If we look at AppcompatButton.java, we see that the default button style is defined by buttonStyle
attribute:
public AppCompatButton(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.buttonStyle);
}
Now that we know this, we can extract the state list animator from the theme as follows:
// 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
}
It is also possible to let the button default to the state list animator by not setting it to @null
. You can then capture the value in code, save it and set the animator to null also in code. You can then replace the capture state list animator value when you want.

Cheticamp
- 61,413
- 10
- 78
- 131