StateListDrawable可能大家比较陌生,当时<selector></selector>大家一定很熟悉,StateListDrawable就是<selector></selector>对应的类。它是由多个条件选择图片,组成一个整体的图形!每一个item对应一种状态匹配,以及这种状态下的drawable资源。
每次状态发生改变时,都会从上到下遍历这个状态列表,第一个和它匹配将会被调用,而不是再适合的。
下面是所有的状态列表:
<item>属性:
android:drawable 必须的,指向一个drawable资源android:state_pressed Boolean。是否按下android:state_focused Boolean。是否获得获得焦点android:state_hovered Boolean。鼠标在上面滑动的状态。通常和state_focused使用同样的drawable api14后新增的android:state_selected Boolean。是否选中android:state_checkable Boolean。是否可以被勾选(checkable)。只能用在可以勾选的控件上android:state_checked Boolean。是否被勾选上android:state_enabled Boolean。是否可用android:state_activated Boolean。是否被激活并持久的选择 api11后新增android:state_window_focused Boolean。当前应用程序是否获得焦点<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@color/black"></item>
<item android:drawable="@color/white"></item>
</selector>
xml布局中引用:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"
android:background="@drawable/selector"/>纯代码实现:
StateListDrawable drawable=new StateListDrawable();
drawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(R.color.black));
drawable.addState(new int[]{}, getResources().getDrawable(R.color.white));
Button btn=(Button) findViewById(R.id.btn);
btn.setBackground(drawable);
本文深入探讨了StateListDrawable在Android开发中的使用,包括其基本概念、关键属性和代码实例,帮助开发者掌握如何利用它来创建响应不同状态的动态UI。
1222

被折叠的 条评论
为什么被折叠?



