AppCompatActivity 下的按钮不会在运行时自动更改为 AppCompatButton?

问题描述

据说 Button 将转移到 AppCompatActivity 下的 AppCompatButton,但我发现这对我来说没有发生。与此处Android Button background color not changing相同的问题。

在这里检查了https://developer.android.com/reference/androidx/appcompat/widget/AppCompatButton

This will automatically be used when you use Button in your layouts and the top-level activity / dialog is provided by appcompat. You should only need to manually use this class when writing custom views.

“编写自定义视图时,您应该只需要手动使用此类。”是什么意思?

更新:

  1. 首先,您应该知道您基于哪个主题,“Theme.MaterialComponents.DayNight.DarkActionBar”或“Theme.AppCompat.Light.NoActionBar”,检查主题或样式文件
  2. 对于 AS4.1,向导创建的项目将使用材料设计
  3. 对于填充按钮,此类使用主题的 ?attr/colorPrimary 作为背景色调颜色,使用 ?attr/colorOnPrimary 作为文本颜色。对于未填充的按钮,此类使用 ?attr/colorPrimary 作为文本颜色,使用透明作为背景色调。
  4. 请在此处阅读更多信息https://developer.android.com/reference/com/google/android/material/button/MaterialButton
  5. 请记住,不仅是 Button,还有所有小部件,Material Design 使用了完全不同的方式

解决方法

Button 将在 AppCompatButton

下转移到 AppCompatActivity

这是不正确的。
这取决于您的活动中使用的主题

如果使用 MaterialComponents.* 主题,MaterialComponentsViewInflater 会在膨胀时用 Material Components 替换一些框架小部件。

带有AppCompatAppCompatViewInflater 主题也会发生类似的情况。 您可以检查 MaterialComponentsViewInflater extends AppCompatViewInflater