這幾天在做一個小軟件,做的按鈕本來是干巴巴的Button,就是白底黑字的按鈕,但是背景用圖片做了,按鈕還是這樣就很不美觀了。我想到了用ImageButton,但是又發現不能設置文字而且ImageButton的圖片不能自適應大小,難不成要自己按照分辨率做一個帶文字的圖片?這樣明顯不行,最后還是在別人的一個仿微信的軟件的源碼里找到了答案。近乎完美地解決了我的問題,不僅可以在圖片上添加文字,而且圖片可以自適應不通的分辨率,同時可以增加按下和選中(獲得焦點)效果,忍不住贊一個。在這里記錄一下。
一般初學安卓,我們的Button的設置都是ID、layoutwidth、layoutheight、text等,需要的時候可以設置background,但是初學一般background引用的就是一個圖片
1 android:backgronud="@drawable/pic0"
這樣顯然太過死板了,而且不能很好地匹配不同的手機屏幕。那么如何解決呢?
這里就是利用這個background的引用,設置一個Button.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 3 4 <item android:drawable="@drawable/focused" android:state_focused="true"/> 5 <item android:drawable="@drawable/pressed" android:state_pressed="true"/> 6 <item android:drawable="@drawable/pressed" android:state_selected="true"/> 7 <item android:drawable="@drawable/normal"/> 8 9 </selector>
然后在Button的background后面引用這個Button.xml
1 android:background="@drawable/Button"
這樣以來這個Button就擁有了按下和選中效果,同時也可以自由設置text。
下面是一個例子,兩個Button,可以檢驗選中和按下效果,沒有設置text,可以自行添加。
main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:layout_width="50dp" 9 android:layout_height="50dp" 10 android:background="@drawable/button" /> 11 12 <Button 13 android:layout_width="50dp" 14 android:layout_height="50dp" 15 android:background="@drawable/button" /> 16 17 </LinearLayout>
button.xml
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/p1" android:state_focused="true"/> <item android:drawable="@drawable/p2" android:state_pressed="true"/> <item android:drawable="@drawable/p2" android:state_selected="true"/> <item android:drawable="@drawable/p0"/> </selector>
