android - 具有背景颜色的按钮的 Material 效果

标签 android android-5.0-lollipop

我正在使用 Android v21 支持库。

我创建了一个带有自定义背景颜色的按钮。当我使用背景颜色时,波纹、显示等 Material 设计效果消失了(点击时的高度除外)。

 <Button
 style="?android:attr/buttonStyleSmall"
 android:background="?attr/colorPrimary"
 android:textColor="@color/white"
 android:textAllCaps="true"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Button1"
 />

Background 下面是一个普通的按钮,效果很好。

<Button
 style="?android:attr/buttonStyleSmall"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:textAllCaps="true"
 android:text="Button1"
/>

Default button

最佳答案

当您使用 android:background 时,您正在用空白颜色替换按钮的大部分样式和外观。

更新:version 23.0.0 release 开始的 AppCompat ,有一个新的Widget.AppCompat.Button.Colored将主题的 colorButtonNormal 用于禁用颜色,将 colorAccent 用于启用颜色的样式。

这允许您直接将其应用到您的按钮

<Button
  ...
  style="@style/Widget.AppCompat.Button.Colored" />

如果您需要自定义 colorButtonNormalcolorAccent,您可以使用 ThemeOverlay,如 this pro-tip 中所述和 android:theme 在按钮上。

上一个答案

您可以在 v21 目录中使用可绘制对象作为背景,例如:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorPrimary"/>
</ripple>

这将确保您的背景颜色为 ?attr/colorPrimary 并且使用默认的 ?attr/colorControlHighlight 具有默认的波纹动画(您也可以在主题中设置)如果你愿意)。

注意:您必须为低于 v21 创建一个自定义选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/primaryPressed" android:state_pressed="true"/>
    <item android:drawable="@color/primaryFocused" android:state_focused="true"/>
    <item android:drawable="@color/primary"/>
</selector>

假设您对默认、按下和聚焦状态有一些您想要的颜色。就个人而言,我在被选中的过程中截取了一个涟漪的屏幕截图,并将主要/聚焦状态从中拉出来。

关于android - 具有背景颜色的按钮的 Material 效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26686250/

相关文章:

android - 如何在android中为纵向和横向模式提供单独的布局

java - 如何在运行时设置textview位置常量?

android - java.lang.StackOverflow Error for Android L预览跑图

Android 推送通知服务未在 Lollipop 上启动

android - 公共(public)静态最终 int 13687=0x7f020000;错误

android - 使用 Toolbar + TabLayout 为 AppBarLayout 充气

Android USB_DEVICE_ATTACHED 持久权限

android - EditText lineSpacing 异常的行为

android - 在 Android 5+ 中使用 MediaCodec 进行的视频解码损坏

android - 检查 Android 用户的 "when device is locked"通知设置