$Android自定义控件在不同状态下的属性
在寫代碼的時(shí)候,有時(shí)候需要控件在不同狀態(tài)下顯示不同的外觀,比如在按鈕按下的時(shí)候要變顏色,EditText獲取焦點(diǎn)時(shí)候邊框要變顏色等。那么下面就來(lái)梳理一下這些是怎么實(shí)現(xiàn)的。
(一)按鈕按下時(shí)候變顏色
1、在項(xiàng)目的drawable目錄下創(chuàng)建selector_title_imagebutton_bg.xml文件,內(nèi)容如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 3 4 <!-- title欄ImageButton按下去時(shí)候的顏色 --> 5 <item android:drawable="@drawable/LightBlue" android:state_pressed="true"/> 6 7 <!-- title欄ImageButton正常時(shí)候的顏色 --> 8 <item android:drawable="@drawable/ThemeDefault"/> 9 10 11 <!-- 注:LightBlue和ThemeDefault都是在color.xml文件中定義的drawable類型的顏色值 --> 12 13 </selector>2、在values目錄下styles.xml文件中增加一個(gè)style項(xiàng),如下:
1 <!-- 標(biāo)題欄ImageButton的style --> 2 <style name="TitleIbStyle" parent="@android:style/Widget.ImageButton"> 3 <item name="android:background">@drawable/selector_title_imagebutton_bg</item> 4 </style>3、在布局xml文件中,創(chuàng)建ImageButton時(shí)只需設(shè)置其style屬性為"TitleIbStyle"即可:
1 <ImageButton 2 android:id="@+id/title_base_left_ib" 3 style="@style/TitleIbStyle" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content" 6 android:padding="5dp" />
(二)EditText獲取焦點(diǎn)時(shí)候邊框變顏色
1、在項(xiàng)目的drawable目錄下新建一個(gè)selector_edittext_bg.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/et_pressed" android:state_focused="true"/> 5 <item android:drawable="@drawable/et_normal"/> 6 7 <!-- 注:et_pressed和et_normal是drawable目錄下兩張相同大小、填充顏色都為白色但邊框顏色不同的圓角矩形的png圖片 --> 8 9 </selector>2、在values目錄下styles.xml文件中增加一個(gè)style項(xiàng),如下:
1 <!-- EditText的自定義風(fēng)格 --> 2 <style name="MyEtStyle" parent="@android:style/Widget.EditText"> 3 <item name="android:background">@drawable/selector_edittext_bg</item> 4 </style>3、在布局xml文件中,創(chuàng)建EditText時(shí)只需設(shè)置其style屬性為"MyEtStyle"即可:
1 <EditText 2 android:id="@+id/content_et" 3 style="@style/MyEtStyle" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content"
(三)總結(jié)
通過(guò)上述方式,其實(shí)還可以實(shí)現(xiàn)很多種其他的自定義效果,有待進(jìn)一步探索。
?
轉(zhuǎn)載于:https://www.cnblogs.com/jiayongji/p/5373610.html
總結(jié)
以上是生活随笔為你收集整理的$Android自定义控件在不同状态下的属性的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Sublime Text 3实用快捷键大
- 下一篇: Android特效 五种Toast详解