從源碼分析 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

相關文章
相關標籤/搜索