文章转载自 https://www.jianshu.com/p/66c6a97a8d80
在 Android 5.0 以上的设备中,API 提供的 Button 样式自带了 Material Design 风格,默认的颜色还是灰色。但在大多数情况下我们需要修改 Button 的颜色来适应我们应用的整体风格。
当我们和往常一样通过设置 android:background
属性来改变 Button 的颜色后,实际应用发现 Button 失去了 Material Design 效果,变得很一般。当尝试用 selector
来实现时,发现处理过程工作量不少,而且效果也不明显。
那么如何修改默认 Button 的颜色,而不改变默认 Button 的其它特性呢?
1、追踪默认 Button 样式是如何设置的?
在 .../res/styles.xml
文件中我们可以看到应用默认的style
继续跟踪 Theme.AppCompat.Light.DarkActionBar
<style name="Theme.AppCompat.Light.DarkActionBar" parent="Base.Theme.AppCompat.Light.DarkActionBar"/>
继续跟踪 Base.Theme.AppCompat.Light.DarkActionBar
继续跟踪 Base.Theme.AppCompat.Light
,会提示有不同版本,通过一一跟踪,最终继承的 parent style 都是 Base.V7.Theme.AppCompat.Light
发现其中设置了 buttonStyle
,继续跟踪 Widget.AppCompat.Button
<style name="Widget.AppCompat.Button" parent="Base.Widget.AppCompat.Button"/>
继续跟踪 Base.Widget.AppCompat.Button
,不同版本有不同的实现
可以看到针对不同版本分别设置了 Button 的样式。
2、通过 buttonStyle 对 Button 颜色进行设置
通过上面的分析过程得知,我们可以通过 buttonStyle
属性来指定 Button 的样式。
而在V7支持包中,提供了5个预置的 Button 的 Style,如下:
3.2、单个具体 Button 设置
在 styles.xml 文件中新建 Style,继承应用 Style,在其中设置 buttonStyle,并通过相应的属性修改 Button 的背景色或文字颜色。然后在需要修改的 Button 中添加 android:theme
属性,引用新建的 Style 即可
在 layout 中使用
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button_1"
android:theme="@style/RedButton" />
4、修改 Button 圆角大小
目前只找到了全局修改 Button 圆角大小的方法在 dimes.xml
文件中复写 abc_control_corner_material
的值,可以修改应用内所有 Button 的圆角大小
<dimen name="abc_control_corner_material" tools:override="true">8dpdimen>
文章只是作为个人记录学习使用,如有不妥之处请指正,谢谢。
文章转载自 https://www.jianshu.com/p/66c6a97a8d80