Android为按钮添加边框而不会丢失材料主题(使用可绘制对象)



我有一个简单的按钮

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/add"
android:backgroundTint="@color/add_bg"
android:textColor="@color/add_fg"
<!--android:borderColor?="@color/button_border"-->
android:text="@string/add"/>

我想要白色背景,蓝色文字和蓝色边框。我知道我可以通过此处和许多其他地方所示的可绘制对象来实现这一点。但是,我观察到,如果向按钮添加可绘制对象,那么它将失去其所有材质属性(例如阴影以及单击具有花哨的波纹动画时(。那么如何在按钮周围添加边框而不会丢失材质主题动画(单击时的阴影和提示动画(?

android 附带的大多数项目只是一组预先打包的属性。

几乎不可能期望 Android API 开发人员为每种可能的颜色/边框组合包含一组预先打包的属性,但总有一个解决方案!

不幸的是,正如您提到的,解决方案确实存在于创建您自己的自定义XML文件,在您掌握它之前,这通常令人生畏。一旦你这样做了,你也会惊叹于它所允许的灵活性。

专门针对您的情况,有两种选择...

1( 创建自定义 XML 边框可绘制对象。

2(在按钮背景属性下设置新的自定义边框可绘制对象

3(然后还通过添加以下内容在按钮XML属性下设置涟漪效果:

android:foreground="?attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"

----或----

更复杂的方法是制作如下所示的可绘制对象。这将添加"波纹"按钮效果以及自定义阴影、按钮颜色和边框颜色!

"对于以后阅读本文的任何人来说,可能经验不足(

1(在项目视图中,转到 res/drawable

2(右键单击文件夹本身,然后选择新建/可绘制的资源文件

3(输入文件名my_ripple_button.xml(根并不重要,因为您将用以下代码替换它(

4(单击文本选项卡(如果您还没有(

5(选择所有文本并基本替换为以下内容:(创建自定义颜色边框的步骤基本相同(

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorPrimaryDark">
<item android:id="@android:id/ripple">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimaryDark" />
<corners android:radius="@dimen/button_radius_large" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="@color/colorPrimaryLight"
android:startColor="@color/colorPrimary"
android:type="linear" />
<corners android:radius="@dimen/button_radius_large" />
</shape>
</item>
</ripple>

最新更新