1

我想在运行时动态更改键盘键背景。但状态列表drawable在KeyboardView类的onDraw方法中不起作用。 我写的代码是 -StateListDrawable不能在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); 
     } 
    } 
} 

请帮帮我。

+0

你在哪里改变状态的状态可绘制的? – pskink

+0

在按钮背景中,我不需要改变状态。 clickMeButton.setBackgroundDrawable(states)是工作。在键盘视图中,是否需要更改stateListDrawable的状态?我该如何改变它? –

+0

我看到你正在创建一个新的'StateListDrawable'并将它用于'Canvas'绘图,而不是在任何其他地方使用它 – pskink

回答

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); 
} 
相关问题