Android_selector背景选择器的用法

本文详细解析了如何使用Selector实现Button背景切换,包括点击、形状自定义等特性,提供了实例代码和注意事项,适合Android开发者深入理解Button背景效果的定制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Selector背景选择器可以帮助我们切换自定义的背景风格,用于buttonListView布局点击时候的背景切换

Selector包含一个或多个item元素

常用item的属性:

<item>

      android:state_focused   ==》true表示获得焦点时显示(例如用滚动球聚焦button),false表示没获得焦点时显示默认  

     android:state_window_focused==》true表示应用程序窗口有焦点时使用;false表示无焦点时使用(例如Notification栏拉下或对话框显示)

     "true" if this item should be used when the application window has focus (the application is in the foreground), "false" if this item should be used when the application window does not have focus (for example, if the notification shade is pulled down or a dialog appears).

     android:state_enabled==》true表示object(组件)能使用时(显示该图片)(能够接受触摸事件和单击事件),false表示该组件不能使用时(显示该图片)

     android:state_pressed ==》true表示当object被按下(例如一个按钮被触摸若点击)时使用(显示按下图片)false表示没被按下时显示默认(图片)

      android:state_checkable ==》true表示当组件被选中时使用,false:组件没被选中时使用

       "true" if this item should be used when the object is checkable; "false" if this item should be used when the object is not checkable. (Only useful if the object can transition between a checkable and non-checkable widget.)

     android:state_checked ==》true表示被选中时使用,false表示没被选中时使用

     "true" if this item should be used when the object is checked; "false" if it should be used when the object is un-checked true表示当checkbox选中时显示该图片,false当checkbox

     android:state_selected ==》true表示当组件被选择时使用(例如当一个tab组件被选中),false当组件未被选择时使用

     "true" if this item should be used when the object is selected (such as when a tab is opened); "false" if this item should be used when the object is not selected. 

</item>


下面先从自定义button背景风格展开(ListView和布局的以后会补上)

一、button的背景效果

1.点击button背景图的切换

如果要设置点击button,button背景切换的话,最简单的方法就是只需要两个item标签就可以搞定:

【注意点微笑^_<耐心读下去啦】注意item的顺序,第一个匹配当前状态的item会被使用,因为有item已经实现了,所以就会返回不去执行下面的item,就像程序里的if语句一样。所以返回条件限制越细致的要放在前面,而对于默认条件下的item必须放在最后面。拿上面的那个例子来说,如果你把最后一句默认显示图片btn_n的item语句放在最上面,那么当你点击按钮的时候是不会有按下去的效果的,因为点击按钮后item实现了第一句默认显示图片,就返回了,state_pressed不会被触发,就没有按下去的效果。所以item的顺序要关注哦~


2.用shape自定义button的风格

这个给个链接吧,我觉得以后用到的不多,因为这样的按钮其实蛮费时的还不一定美观,还是选择ps吧

点击链接:Android Selector与shape基本用法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值