Android selector 疑问

2016-11-09 13:36:15 +08:00
 pcatzj

想请问一下, Android 的 selector 能不能设置点击时是一种背景,但是不点击时不设置背景?如果可以,那应该怎么设置?我在 selector 里面直接设置的 @null 报错。

5492 次点击
所在节点    Android
9 条回复
jimbray
2016-11-09 14:04:58 +08:00
有一个取巧的办法 color.xml 新建一个 #00000000 的 drawable
selector 里面直接 设置 @drawable/xxxx 即可
pcatzj
2016-11-09 14:07:47 +08:00
@jimbray 好的,感谢,我试试
pcatzj
2016-11-09 14:15:53 +08:00
不行,这样的话选中状态的效果也不生效了
pcatzj
2016-11-09 14:16:10 +08:00
@jimbray 不行,这样的话选中状态的效果也不生效了
zhaohui318
2016-11-09 18:50:11 +08:00
Note: Remember that the first item in the state list that matches the current state of the object will be applied. So if the first item in the list contains none of the state attributes above, then it will be applied every time, which is why your default value should always be last, as demonstrated in the following example.

https://developer.android.com/guide/topics/resources/color-list-resource.html

default 要放在最后面
jimbray
2016-11-10 08:58:43 +08:00
@pcatzj 楼上说的对。
pcatzj
2016-11-10 16:13:52 +08:00
@zhaohui318
@jimbray
是放在最后的,我一般习惯都是把最后默认的写在最后,但是不管是设置 @null 还是#00000000 还是不写默认的都不行
zhaohui318
2016-11-10 19:00:11 +08:00
检查一下你的代码是不是哪里没写对
我试了下 default 的可以不写

EXAMPLE:

XML file saved at res/drawable/button.xml:

<?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/button_pressed" /> <!-- pressed -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

This layout XML applies the state list drawable to a Button:

<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Hello World!"
android:background="@drawable/button" />
pcatzj
2016-11-11 09:47:46 +08:00
@zhaohui318 不写的效果是什么呢,我试的时候是选中时的效果也没有了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/319238

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX