我正在将 KeyboardView 用于自定义键盘。我正在尝试更改键的背景颜色。我尝试使用 java 代码,但它没有按预期工作。这是我的代码。
以编程方式创建可绘制对象:
public StateListDrawable getSelectorDrawable() {
StateListDrawable out = new StateListDrawable();
out.addState(new int[] { android.R.attr.state_pressed }, createDrawable(Color.GREEN));
out.addState(new int[] { android.R.attr.state_focused }, createDrawable(Color.GREEN));
out.addState(new int[] { android.R.attr.state_enabled }, createDrawable(Color.BLUE));
return out;
}
public GradientDrawable createDrawable(int color) {
GradientDrawable out = new GradientDrawable();
out.setShape(GradientDrawable.RECTANGLE);
out.setGradientType(GradientDrawable.LINEAR_GRADIENT);
out.setColor(color);
out.setStroke(2, color);
out.setCornerRadius(0F);
return out;
}
调用方法创建Drawable:
private void drawKeyBackground(Canvas canvas, Keyboard.Key key) {
Drawable npd = getSelectorDrawable();
int[] drawableState = key.getCurrentDrawableState();
if (key.codes[0] != 0) {
npd.setState(drawableState);
}
npd.setBounds(key.x, key.y, key.x + key.width, key.y
+ key.height);
npd.draw(canvas);
}
public class CustomKeyBoard extends KeyboardView {
Context context;
@Override
public void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
List<Keyboard.Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
if (key.codes[0] == 53) {
drawKeyBackground(canvas, key);
drawText(canvas, key);
}
}
}
这里 press_state 颜色正在工作。但是 normal_state 颜色不起作用。请给我一些想法来解决这个问题。
OP:正常状态:
OP:专注状态: