在很多Android APP中,我們都能看的這種上面圖標、下面文字的按鈕,並且當手指觸摸時,是有一個圖標背景顏色改變的效果。那麼,它是怎麼實現的呢?
首先,定義佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fadai.icontopbutton.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:padding="4dp"
android:gravity="center"
android:text="刪除"
android:textSize="12sp"
android:textColor="#FFF"
android:drawableTop="@drawable/delete_btn_bg"
/>
</LinearLayout>
</RelativeLayout>
沒什麼要注意的,主要是TextView的 android:drawableTop 這個屬性。它是在textView的上面繪製一個圖形,可以是圖片,也可以是自己在drawable文件夾中繪製的圖形。同樣,還有drawableLeft、drawableRight等。
那麼,我們在drawable中創建delete_btn_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--手指未觸摸-->
<item android:state_pressed="false">
<layer-list>
<item>
<!--繪製 圓形-->
<shape
android:shape="oval">
<!--填充顏色-->
<solid android:color="@color/colorPrimary"/>
<!--描邊 白色 寬度1px-->
<stroke android:color="#FFF"
android:width="1px"/>
<!--內容與該圓形的間距-->
<padding android:bottom="8dp" android:left="8dp" android:right="8dp" android:top="8dp"/>
/>
</shape>
</item>
<!--導入圖片 -->
<item android:drawable="@drawable/ic_delete_white_24dp"/>
</layer-list>
</item>
<!--手指觸摸-->
<item android:state_pressed="true">
<layer-list>
<item>
<shape
android:shape="oval">
<solid android:color="@color/colorPrimaryDark"/>
<stroke android:color="#FFF"
android:width="1px"/>
<padding android:bottom="8dp" android:left="8dp" android:right="8dp" android:top="8dp"/>
/>
</shape>
</item>
<item android:drawable="@drawable/ic_delete_white_24dp"/>
</layer-list>
</item>
</selector>
這個略複雜,註釋已經很清楚了,繪製一個圓形,再導入刪除圖標,就行了。並且,對手指觸摸和未觸摸時的填充顏色進行了區別。
好了,我們看下效果:
樣子是有了,可我們點擊的時候卻沒有出現變色的效果。 原來TextView默認是不可以點擊的,我們可以給TextView一個android:clickable="true” 的屬性。
修改後的效果:
可以看到,點擊時,是有我們預先設定的這樣一個效果的。