1. 程式人生 > >Android水波紋點選效果

Android水波紋點選效果

轉:Android水波紋點選效果

Android API 21及以上新增了ripple標籤用來實現水波紋的效果。我們可以通過設定ripple背景來實現一些View點選效果。

水波紋樣圖

1. 水波紋效果實現

1)系統效果

  • 系統有界效果
    API 21以上使用,才有波紋效果;API 21以下使用只有變色效果,沒有波紋效果
android:background="?android:attr/selectableItemBackground"
  • 系統無界效果
    API 21以上才能使用,API 21以下會報錯無法編譯,最小版本要設定為minSdkVersion 21
android:background="?android:attr/selectableItemBackgroundBorderless"

2)自定義效果
res中新建一個drawable-v21資料夾,在此資料夾下新建ripple_bg.xml用於實現波紋效果。(僅限Android 5.0以上機型)

  • 自定義有界效果
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/gray"> <!--波紋顏色-->
      <item>
        <shape android:shape="rectangle">
            <!-- 填充背景色-->
            <solid android:color="@color/white"/>
        </shape>
    </item>
</ripple>
  • 自定義無界效果
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/gray"> <!--波紋顏色-->   
</ripple>
  • 自定義帶圖片效果
<?xml version="1.0" encoding="utf-8"?>  
<ripple xmlns:android="http://schemas.android.com/apk/res/android" 
        android:color="@color/gray">    <!--波紋顏色-->   
   <item>
        <selector>
             <!-- 未點選背景圖-->
            <item
                android:drawable="@drawable/normal_bg"
                android:state_pressed="false" />
             <!-- 點選背景圖-->
            <item
                android:drawable="@drawable/select_bg"
                android:state_pressed="true" />
        </selector>
    </item>
</ripple>

在佈局中使用:

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_bg"/>

2. 水波紋效果相容

在API 21以下無法使用ripple標籤來實現波紋效果,為了相容低版本機型不出錯,我們需要做波紋效果適配。
1)系統效果(只有變色效果,沒有波紋效果)

android:background="?android:attr/selectableItemBackground"

2)自定義效果(只有變色效果,沒有波紋效果)
drawable檔案下建立同名檔案ripple_bg.xml用於適配Android 5.0以下機型。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <!-- 單擊時的背景顏色 -->
    <item
        android:drawable="@color/gray"
        android:state_pressed="true">
    </item>
  <!-- 未單擊時的背景顏色 -->
    <item
        android:drawable="@color/white"
        android:state_pressed="false">
    </item>
</selector>

在佈局中使用:

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_bg"/>