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



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

请帮帮我。

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

相关内容

  • 没有找到相关文章

最新更新