android:theme 应用于特定按钮时应用程序崩溃

App crash when android:theme is aplied to a specific button

我正在为 android(我的第一个应用程序)做一个简单的计算器应用程序,当我尝试将特定的 android:theme 应用于按钮时,我遇到了让我头疼的问题。

当具有特定主题的按钮尝试在 onclick 事件中执行 activity 方法时,问题就出现了。根据我在 Whosebug 中搜索的内容,具有特定主题的按钮的 "context" 与 activity 上下文不同,因此它无法找到我处理 onclick 的方法在 activity.

我的 style.xml 定义了我的应用程序主题和我的特定按钮主题:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="colorButtonNormal">#dc000000</item>
        <item name="android:background">#dc262626</item>
        <!-- Customize your theme here. -->
    </style>

    <style name="contextButtonTheme" parent="AppTheme">
        <item name="colorButtonNormal">@color/contextButtonsColor</item>
    </style>

</resources>

布局中有我的按钮xml:

<Button
    android:layout_width="0dp"
    android:layout_weight="25"
    android:layout_height="match_parent"
    android:text="X"
    android:id="@+id/multButton"
    android:textSize="11pt"
    android:theme="@style/contextButtonTheme"
    android:onClick="onClickButton"/>

我在此处阅读的解决方案是将 "android:theme" 更改为 "style",虽然这解决了崩溃问题,但未应用 colorButtonNormal 新颜色:(.

请帮助我 D:

PD:抱歉我的英语不好

我已经回答了一个类似的问题 ,您可以在其中了解更多背景知识。

您的问题的一个可能解决方案是不使用 android:onClick="onClickButton",而是在代码中设置 onClickListener。这样你就可以保持你的主题 Button。官方 docs 有一个如何做到这一点的例子。