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); 
} 
相關問題