StateListDrawable在KeyboardView的OnDraw()方法中不起作用

时间:2015-10-05 08:15:29

标签: android android-canvas android-softkeyboard android-drawable statelistdrawable

我正在尝试在运行时动态更改键盘密钥背景。但是状态列表drawable在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);
        }
    }
}

请帮帮我。

1 个答案:

答案 0 :(得分:1)

我删除了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);
}