前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >从源码分析 Android Button 点击效果

从源码分析 Android Button 点击效果

作者头像
开发者
发布2019-12-26 13:05:25
1.1K0
发布2019-12-26 13:05:25
举报
文章被收录于专栏:Android开发者家园

Android 点击效果

我们平时在开发过程中都可能注意到,我们写的默认的 Button 都是有点击效果的,而且大小也有默认规定的,而 TextView 就没有。就想下面的图片一样。

是有默认效果的。通过查看 Button 的源码我们看到:

每个 button 有系统默认的风格样式,就是这里的风格样式,使得我们的 button 有了这种效果。下面我们来看看系统默认的 button 风格(注意不同的版本风格可能不同,但大体都是一样的)

通过这个构造函数,我们就可以找到 Button 的默认风格了。

这就是我们这里使用的默认 Button 的风格(不知道怎么找的看看我前面关于属性的文章),看到这里 Button 的最小高度,最小宽度都有了,这就解释了为什么默认的 Button 就那么大了。当你自己给 Button 设置一个 background 后,你会发现,你的 button 没有默认的那种波浪效果了。那么我们就猜想到肯定和 background 有关。那么我们来看看 button 的默认 background 是如何写的。

这个就是 background 的默认背景,这里的 ripple标签就是点击波浪效果的关键!然后我们仿照自己写一个 background

代码语言:javascript
复制
<ripple xmlns:android="xxxxxxxxxxx"
       android:color="#fffea50b">
   <item android:drawable="@drawable/bcg" /></ripple><inset xmlns:android="http://schemas.android.com/apk/res/android"
      android:insetLeft="4dp"
      android:insetTop="6dp"
      android:insetRight="4dp"
      android:insetBottom="6dp">
   <shape android:shape="rectangle">
       <corners android:radius="@dimen/abc_control_corner_material" />
       <solid android:color="@android:color/holo_blue_dark" />
       <padding android:left="@dimen/abc_button_padding_horizontal_material"
                android:top="@dimen/abc_button_padding_vertical_material"
                android:right="@dimen/abc_button_padding_horizontal_material"
                android:bottom="@dimen/abc_button_padding_vertical_material" />
   </shape></inset>

好了,这样我们就实现自定义 background 了。其实关于波浪 ripple 的用法还有很多。这里就不再说了,这里只是教大家从源码上分析,借助默认样式,来写出我们的自定义样式。

还有一点,可能会有疑问,那就是 button 下面的阴影效果,其实这里在 5.0 后 Material Design 设计风格。在 Android 5.0 后加入了新的属性 stateListAnimator 使 button 有了阴影效果。具体官方文档:https://developer.android.google.cn/guide/topics/graphics/prop-animation#ViewState 和 https://material.io/design/environment/elevation.html#elevation-shadows-shadows 如果你想去掉这种效果最有效的办法就是 stateListAnimator 的值设置为 @null 当然还有其他办法比如:你可能观察到了上面的 background 的 shape 最外面是 inset ,这样的效果是,如果你设置了 button 的宽 100 高 100 的话,button 的可点击范围是这么大,但是背景是减去 inset 设置的值。这样 button 就有了阴影的空间了。

同样,如果你给你的 TextView 设置了这种风格,那么你的 TextView 就和 button 的样式一样了。好了,现在你就可以完全定义自己的点击效果了!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-12-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Android开发者家园 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Android 点击效果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档