在 Android API<29 中,通过以下方式来为自定义视图获取StateListDrawable状态图形:
其中,customView_pressed、customView_focused和customView_default是自定义视图在不同状态下的图片。
Drawable state1 = context.getResources().getDrawable(R.drawable.customView_state_list);
addState(new int[] { android.R.attr.state_pressed }, state1);
Drawable state2 = context.getResources().getDrawable(R.drawable.customView_state_list);
addState(new int[] { android.R.attr.state_focused }, state2);
Drawable state3 = context.getResources().getDrawable(R.drawable.customView_state_list);
addState(new int[] {}, state3);
在代码片段中,context是自定义视图的上下文,而customView_state_list是前面创建的.xml文件的名称。
int[] stateSet = getDrawableState();
Drawable drawable = getStateDrawable(stateSet);
drawable.draw(canvas);
在代码中,getDrawableState()方法返回当前自定义视图的状态数组,getStateDrawable()方法返回与当前状态匹配的状态图形。最后,使用Canvas对象的draw()方法将图形绘制到自定义视图上。