我在自定义视图中有一堆可绘制对象。我希望用户能够按下一个或多个可绘制对象并更改颜色。目前,每个可绘制对象都只是StateListDrawable
具有两种状态:state_pressed
和未按下。每次我按下可绘制对象时,setState
都会返回 true,因此我假设它实际上已更改,但我没有看到可绘制图像更改。是invalidateDrawable
不是什么都不做?我究竟做错了什么?如何在按下时重绘一个drawable而不需要customView.invalidate()
每次都调用和重绘整个东西?我最初是这样做的,但发现我的应用程序运行非常缓慢/效率低下。谢谢!
流量:
Custom View (contains set of our custom class - TouchKey)
- Custom class TouchKey containing drawable and info
- Upon press or release, custom class finds which drawable to change
这是类中按钮触摸的代码TouchKey
(MyTouch 是一个自定义类,用于跟踪 android 设备上的所有触摸):
public void pressed(MyTouch touch) {
boolean successfulStateChange = this.drawable.setState(new int[]{android.
R.attr.state_pressed});
this.customView.invalidateDrawable(drawable);
}
public void released(MyTouch touch) {
boolean successfulStateChange = this.drawable.setState(new int[]{-android.
R.attr.state_pressed});
this.customView.invalidateDrawable(drawable);
}
我是如何StateListDrawable
在我的自定义视图中绘制的:
public class CustomView extends View {
private TreeMap<Integer, TouchKey> keymap;
/* Initialization Code Stuff Here - call drawKey */
// StateListDrawable Creation
private StateListDrawable drawKey(Canvas canvas, int bounds_l,
int bounds_t, int bounds_r, int bounds_b)
throws Resources.NotFoundException, XmlPullParserException, IOException {
StateListDrawable key = new StateListDrawable();
key.addState(new int[]{android.R.attr.state_pressed},
ContextCompat.getDrawable(mContext, R.drawable.key_pressed));
key.addState(new int[]{-android.R.attr.state_pressed},
ContextCompat.getDrawable(mContext, R.drawable.key_released));
key.setBounds(bound_l, bounds_t, bounds_r, bounds_b);
key.draw(canvas);
return key;
}
}