StateListDrawable是Android中一种特殊的Drawable资源,它可以根据视图的不同状态显示不同的Drawable。下面我将详细介绍如何以编程方式创建和使用StateListDrawable。
StateListDrawable是一个包含多个Drawable对象的资源,每个Drawable对应视图的一种或多种状态组合(如按下、聚焦、选中等)。当视图状态改变时,系统会自动切换到对应的Drawable。
// 创建StateListDrawable对象
StateListDrawable stateListDrawable = new StateListDrawable();
// 添加不同状态对应的Drawable
int pressed = android.R.attr.state_pressed;
int focused = android.R.attr.state_focused;
int normal = -android.R.attr.state_pressed; // 负值表示不匹配该状态
// 创建不同状态的Drawable
Drawable pressedDrawable = new ColorDrawable(Color.RED);
Drawable focusedDrawable = new ColorDrawable(Color.BLUE);
Drawable normalDrawable = new ColorDrawable(Color.GREEN);
// 添加状态-Drawable对
stateListDrawable.addState(new int[]{pressed}, pressedDrawable);
stateListDrawable.addState(new int[]{focused}, focusedDrawable);
stateListDrawable.addState(new int[]{normal}, normalDrawable);
// 应用到View
view.setBackground(stateListDrawable);
StateListDrawable stateListDrawable = new StateListDrawable();
// 从资源加载Drawable
Drawable pressedDrawable = ContextCompat.getDrawable(context, R.drawable.btn_pressed);
Drawable normalDrawable = ContextCompat.getDrawable(context, R.drawable.btn_normal);
// 添加状态
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);
stateListDrawable.addState(new int[]{}, normalDrawable); // 默认状态
// 组合多个状态条件
stateListDrawable.addState(
new int[]{
android.R.attr.state_pressed,
android.R.attr.state_enabled
},
enabledPressedDrawable
);
| 状态属性 | 描述 |
|---------|------|
| android.R.attr.state_pressed
| 按下状态 |
| android.R.attr.state_focused
| 获得焦点状态 |
| android.R.attr.state_selected
| 选中状态 |
| android.R.attr.state_checkable
| 可勾选状态 |
| android.R.attr.state_checked
| 已勾选状态 |
| android.R.attr.state_enabled
| 启用状态 |
| android.R.attr.state_window_focused
| 窗口获得焦点状态 |
new int[]{}
setEnterFadeDuration()
和setExitFadeDuration()
添加过渡动画// 在res/values/attrs.xml中定义自定义属性
<resources>
<attr name="state_custom" format="boolean" />
</resources>
// 代码中使用
StateListDrawable stateListDrawable = new StateListDrawable();
int[] customState = {R.attr.state_custom};
// 添加自定义状态
stateListDrawable.addState(customState, customDrawable);
// 在自定义View中设置状态
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
// 刷新Drawable状态
refreshDrawableState();
}
通过编程方式创建StateListDrawable提供了更大的灵活性,特别适合需要动态生成UI元素的场景。
没有搜到相关的文章