过时的答案。 请检查 VinceStyling 的答案,以获得使用 SDK 29+ 的更好解决方案
没有没有公共API可以从状态获取可绘制对象。
StateListDrawable
中有一些方法,但它们是@hide
,带有注释“待定的API委员会”。
您可以通过反射来调用它们...但是您需要自行承担风险!!!。 (在未来的版本中可能会改变)
这些方法是:以下是如何进行(省略例外):
int[] currentState = view.getDrawableState();
StateListDrawable stateListDrawable = (StateListDrawable)view.getBackground();
Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class);
Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class);
int index = (int) getStateDrawableIndex.invoke(stateListDrawable,currentState);
Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable,index);
StateListDrawable pressedDrawable = (StateListDrawable) this.mPressed;
final int state = android.R.attr.state_pressed;
final int index = pressedDrawable.findStateDrawableIndex(new int[]{state});
if (index >= 0) {
Drawable drawable = pressedDrawable.getStateDrawable(index);
if (drawable instanceof GradientDrawable) {
((GradientDrawable) drawable).setCornerRadius(mRoundConerRadius);
}
}