【问题标题】:How to reset android:stateListAnimator from null to the default style of the button in Android`如何将android:stateListAnimator从null重置为Android中按钮的默认样式`
【发布时间】:2021-12-26 22:13:48
【问题描述】:

我在 Android 中实现了一个定制的“启用”按钮。当我的按钮被禁用时,我设置了 android:stateListAnimator="@null" 并希望在启用时将其重置为默认的 Widget.AppCompat.Button 样式。但是我怎样才能重置它?我需要设置什么 stateListAnimator ?

【问题讨论】:

    标签: android android-layout android-styles android-developer-api android-layoutparams


    【解决方案1】:

    如果我们查看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。然后,您可以根据需要替换捕获状态列表动画器值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-24
      • 2011-07-24
      • 1970-01-01
      • 2016-01-18
      • 2021-10-06
      • 2013-04-11
      • 2014-02-15
      • 2011-05-17
      相关资源
      最近更新 更多