2

我正在尝试在运行时动态更改键盘键背景。但是状态列表可绘制在 KeyboardView 类的 onDraw 方法中不起作用。我的书面代码是 -

@Override
public void onDraw(@NonNull Canvas canvas) {
    List<Key> keys = getKeyboard().getKeys();
    for (Key key : keys) {
        StateListDrawable states = new StateListDrawable();


        states.addState(new int[]{android.R.attr.state_pressed},
                new ColorDrawable(Color.BLUE));
        states.addState(new int[]{},
                new ColorDrawable(Color.YELLOW));

        states.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
        states.draw(canvas);

        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(24);
        paint.setColor(Color.GRAY);

        if (key.label != null) {
            canvas.drawText(key.label.toString(), key.x + (key.width / 2),
                    key.y + (key.height / 2), paint);
        } else {
            key.icon.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
            key.icon.draw(canvas);
        }
    }
}

请帮我。

4

1 回答 1

2

我删除了 StateListDrawable 并在 onDraw 方法中使用以下条件动态更改背景。

if(key.pressed){
    Drawable dr = new ColorDrawable(Color.BLUE);
    dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
        dr.draw(canvas);
}else{
    Drawable dr = new ColorDrawable(Color.YELLOW);
    dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
        dr.draw(canvas);
}
于 2015-10-05T10:27:22.567 回答