Android如何修改TextInputLayout游标底部气泡颜色与弹窗按钮颜色
实现方案
1. 修改TextInputLayout游标底部气泡为白色
修改accent颜色不生效的原因是当前项目一般使用MaterialComponents系列主题,该场景下对应控制属性已变更,可按需选择以下方案:
- 全局生效方案:在项目主题配置文件(通常为
res/values/themes.xml或res/values/styles.xml)的主App主题中添加如下属性:
<style name="你的App主题名称" parent="Theme.MaterialComponents.*"> <!-- 其他原有属性保持不变 --> <item name="colorControlActivated">@android:color/white</item> <!-- 若使用Material 3主题,额外补充下面的属性 --> <item name="colorPrimary">@android:color/white</item> </style>
- 单个控件生效方案:仅修改指定TextInputLayout的气泡颜色,不影响其他控件:
首先在主题文件中新增自定义样式:
<style name="WhiteCursorTextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.FilledBox"> <item name="materialThemeOverlay">@style/CursorWhiteThemeOverlay</item> </style> <style name="CursorWhiteThemeOverlay"> <item name="colorControlActivated">@android:color/white</item> </style>
然后在布局文件中给对应的TextInputLayout引用该样式即可:
<com.google.android.material.textfield.TextInputLayout style="@style/WhiteCursorTextInputLayout" ... 其他原有属性> <com.google.android.material.textfield.TextInputEditText ... 其他原有属性/> </com.google.android.material.textfield.TextInputLayout>
2. 修改AlertDialog确认/取消按钮为黑色

- 全局生效方案:所有弹窗统一应用黑色按钮样式,在主App主题中新增AlertDialog主题配置:
<style name="你的App主题名称" parent="Theme.MaterialComponents.*"> <!-- 其他原有属性保持不变 --> <item name="alertDialogTheme">@style/BlackButtonAlertDialogTheme</item> </style> <style name="BlackButtonAlertDialogTheme" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog"> <item name="buttonBarPositiveButtonTextColor">@android:color/black</item> <item name="buttonBarNegativeButtonTextColor">@android:color/black</item> <item name="buttonBarNeutralButtonTextColor">@android:color/black</item> </style>
配置后所有通过MaterialAlertDialogBuilder创建的弹窗都会自动生效。
- 单个弹窗修改方案:仅修改指定退出弹窗的按钮颜色:
Kotlin示例:
val exitDialog = MaterialAlertDialogBuilder(this) .setTitle("退出提示") .setMessage("确定要退出应用吗?") .setPositiveButton("确定") { _, _ -> finish() } .setNegativeButton("取消", null) .show() // 手动设置按钮颜色 exitDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK) exitDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK)
Java示例:
AlertDialog exitDialog = new MaterialAlertDialogBuilder(this) .setTitle("退出提示") .setMessage("确定要退出应用吗?") .setPositiveButton("确定", (dialog, which) -> finish()) .setNegativeButton("取消", null) .show(); // 手动设置按钮颜色 exitDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK); exitDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
内容的提问来源于stack exchange,提问作者Gokul
相关产品推荐
相关产品推荐

