从源码分析 Android Button 点击效果

Android 点击效果

new.gif

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

GIF.gif

是有默认效果的。经过查看 Button 的源码咱们看到:android

源码说明.jpg

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

风格.jpg

经过这个构造函数,咱们就能够找到 Button 的默认风格了。函数

button默认风格.jpg

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

默认背景.jpg

这个就是 background 的默认背景,这里的 ripple标签就是点击波浪效果的关键!而后咱们仿照本身写一个 backgroundgoogle

<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>        
复制代码

效果图: spa

GIF.gif

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

还有一点,可能会有疑问,那就是 button 下面的阴影效果,其实这里在 5.0 后 Material Design 设计风格。在 Android 5.0 后加入了新的属性 stateListAnimator 使 button 有了阴影效果。具体官方文档:developer.android.google.cn/guide/topic…material.io/design/envi… 若是你想去掉这种效果最有效的办法就是 stateListAnimator 的值设置为 @null 固然还有其余办法好比:你可能观察到了上面的 background 的 shape 最外面是 inset ,这样的效果是,若是你设置了 button 的宽 100 高 100 的话,button 的可点击范围是这么大,可是背景是减去 inset 设置的值。这样 button 就有了阴影的空间了。code

一样,若是你给你的 TextView 设置了这种风格,那么你的 TextView 就和 button 的样式同样了。好了,如今你就能够彻底定义本身的点击效果了!cdn

相关文章
相关标签/搜索