【问题标题】:MaterialButton ClassCastExceptionMaterialButton ClassCastException
【发布时间】:2021-12-05 06:46:57
【问题描述】:

最近,我们开始为我们的应用使用材料设计主题(我们使用的是 1.4.0 版本)。作为其中的一部分,我们将显式的 <com.google.android.material.button.MaterialButton 声明转换为 <Button,因为 Button 将在后台转换为 MaterialButton。除以下情况外,其他一切正常。

我们在FrameLayout 中有一个<com.google.android.material.button.MaterialButton,如下所示

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <Button
      ...
      ...
    />
</FrameLayout>

它通过如下视图绑定被用作自定义视图

class MyView: FrameLayout {

private val binding by ViewGroupBindingProperty(MyViewBinding::inflate)

    constructor(...)
    /// other code
}

当我尝试将上面的

Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to com.google.android.material.button.MaterialButton
        at jp.ne.paypay.android.app.view.paymentMethod.MyView.init(MyView.kt:51)
        at xx.xx.xx.xx.MyView.<init>(MyView.kt:29)

我们非常感谢任何关于可能出现问题的指导。提前谢谢你。

【问题讨论】:

  • 希望this链接对你有帮助
  • @Rustam 谢谢,但我不希望以编程方式创建按钮。我已经有了 XML 中的按钮。它在膨胀和使用它时抛出异常

标签: android material-design android-button material-components-android


【解决方案1】:

我认为您需要将 xml 中的 Button 指定为 com.google.android.material.button.MaterialButton 而不是普通的 Button 尽管这应该由布局充气器在使用材质样式时完成

【讨论】:

  • 感谢您的回答。当前实现使用
【解决方案2】:

@braj 请提供你的完整代码,然后你问为什么

因为Button是Android SDK的一部分,所以你使用的是Material Button那部分Material Design它们是相似的,但是Material Button有很多优点,你可以用Material Design写出漂亮的代码

在您的情况下,您必须将视图实现为 Material Button 而不仅仅是按钮

【讨论】:

  • 我已经用更多细节更新了这个问题。请看一下。使用 AppCompat 主题时,不必专门使用 AppCompatButton、AppCompatTextView 等,只需要指定 Button,后台会自动转换为 AppCompatButton。同样,在使用MaterialCompat主题时,不需要指定MaterialButton、MaterialTextView等,只要提一下Button就够了。我了解并了解 MaterialButton 的优势。我只想知道为什么它在上述情况下不起作用。
  • 所以,我想用例子来解释一下)这里的 MaterialButton 是类 Button 的包装器(这意味着 MaterialButton 类是 Button 类的子类,而 Button 类是 MaterialButton 的父类)所以,MaterialButton 有很多包装器功能,但父类 Button 没有,因为 Button 没有扩展 MaterialButton 所以,您不能将 Button 类转换为 MaterialButton,反之...您可以创建扩展 MaterialButton 的类
  • 如果我回答了您的问题,请标记为已回答,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多