Android按鈕按下的時候改變顏色實現方法
阿新 • • 發佈:2019-02-08
轉載地址:http://www.jb51.net/article/45859.htm
需求是在我按下按鈕時,該變按鈕顏色,使使用者感覺到自己按了按鈕,當鬆開的時候,變回原來的顏色。
正常時:
按下時:
有人說,直接監聽按鈕的按下事件不得了嘛,其實這樣確實能實現同樣的效果,但是有個缺點,比如很多按鈕都需要這樣的效果,那你同樣的程式碼就要重複很多次。所以,還是要通用起來。
首先,在res資料夾下新建一個資料夾drawable,這是無關解析度的:
在下面建立一個xml檔案:login_button_selector.xml
複製程式碼 程式碼如下:<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/clr_normal" android:state_pressed="false"/>
<item android:drawable="@drawable/clr_pressed" android:state_pressed="true"/>
</selector>
然後在value資料夾下的string.xml檔案裡新增:
複製程式碼 程式碼如下:<drawable name="clr_normal">#ff6501</drawable>
<drawable name="clr_pressed">#a44100</drawable>
最後為button新增:
<Button
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/loginSubmit"
android:id="@+id/login"
android:textColor="@android:color/white"
android:background="@drawable/login_button_selector"
/>