Android 自定义Button按钮显示样式(正常、按下、获取焦点)
生活随笔
收集整理的這篇文章主要介紹了
Android 自定义Button按钮显示样式(正常、按下、获取焦点)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
現(xiàn)在的用戶對(duì)APP的外觀看得很重要,如果APP內(nèi)所有元件都用Android默認(rèn)樣式寫(xiě),估計(jì)下面評(píng)論里就有一堆在罵UI丑的。今天學(xué)習(xí)自定義Button按鈕樣式。Button樣式修改的是Button的背景(Background)屬性。首先寫(xiě)一個(gè)定義Button樣式的XML文件:
新建Android XML文件,類型選Drawable,根結(jié)點(diǎn)選selector,文件名就buton_style吧。
程序自動(dòng)給我們剛剛建的文件里加了selector結(jié)點(diǎn),我們只需要在selector結(jié)點(diǎn)里寫(xiě)上三種狀態(tài)時(shí)顯示的背景圖片(按下、獲取焦點(diǎn),正常)。
代碼如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_pressed="true" android:drawable="@drawable/play_press" /><item android:state_focused="true" android:drawable="@drawable/play_press" /><item android:drawable="@drawable/play" /> </selector>
我這里獲取焦點(diǎn)跟點(diǎn)擊時(shí)顯示的是同一張圖片,必須嚴(yán)格照上面的順序?qū)?#xff0c;不可倒。
接下來(lái)只要在布局時(shí)寫(xiě)B(tài)utton控件時(shí)應(yīng)用到Button的Background屬性即可。
<Button android:id="@+id/button1"android:layout_width="wrap_content" android:layout_height="wrap_content"android:background="@drawable/button_style" ></Button>
最終效果圖:
再加上一種自定義樣式方法,上面的是用圖片,其實(shí)我們可以直接通過(guò)定義xml文件來(lái)實(shí)現(xiàn)不同的樣式:
在上面的源代碼基礎(chǔ)上,只需要修改button_style文件,同樣三種狀態(tài)分開(kāi)定義:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_pressed="true"><shape><gradient android:startColor="#0d76e1" android:endColor="#0d76e1"android:angle="270" /><stroke android:width="1dip" android:color="#f403c9" /><corners android:radius="2dp" /><padding android:left="10dp" android:top="10dp"android:right="10dp" android:bottom="10dp" /></shape></item><item android:state_focused="true"><shape><gradient android:startColor="#ffc2b7" android:endColor="#ffc2b7"android:angle="270" /><stroke android:width="1dip" android:color="#f403c9" /><corners android:radius="2dp" /><padding android:left="10dp" android:top="10dp"android:right="10dp" android:bottom="10dp" /></shape></item><item><shape><gradient android:startColor="#000000" android:endColor="#ffffff"android:angle="180" /><stroke android:width="1dip" android:color="#f403c9" /><corners android:radius="5dip" /><padding android:left="10dp" android:top="10dp"android:right="10dp" android:bottom="10dp" /></shape></item> </selector>
gradient 主體漸變 startColor開(kāi)始顏色,endColor結(jié)束顏色 ,angle開(kāi)始漸變的角度(值只能為90的倍數(shù),0時(shí)為左到右漸變,90時(shí)為下到上漸變,依次逆時(shí)針類推)
stroke 邊框 width 邊框?qū)挾?#xff0c;color 邊框顏色
corners 圓角 radius 半徑,0為直角
padding text值的相對(duì)位置
文章出處:http://www.pocketdigi.com/20110623/343.html
轉(zhuǎn)載于:https://my.oschina.net/joeytai/blog/521129
總結(jié)
以上是生活随笔為你收集整理的Android 自定义Button按钮显示样式(正常、按下、获取焦点)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JVM内存的那些事,你了解多少?
- 下一篇: 应用前台省电秘籍——这些常见功耗雷坑不要