2014-01-23 40 views
1

我重寫了我的按鈕類中的onDraw。如何知道內部MyButton :: OnDraw狀態被按下(聚焦)

如何知道onDraw內部按鈕被按下了?

+0

你不應該擴展Button類,則應擴展繪製對象類,而不是 – pskink

+0

任何的例子嗎?這將有助於 – mSO

+0

1)擴展可繪製2)覆蓋isStatefull返回是3)覆蓋onStateChanged獲得當前狀態4)執行繪製方法 – pskink

回答

1

在您的按鈕的onDraw(..)方法,你可以簡單地檢查this.isPressed()
這當按下你的按鈕應返回true

編輯:
您也可以在您觸摸Button's subclass事件:

Example:

public class tempButton extends Button { 

public tempButton(Context context) { 
    super(context); 
    // TODO Auto-generated constructor stub 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    // TODO Auto-generated method stub 
    switch(event.getAction()) 
    { 
     case MotionEvent.ACTION_DOWN: 

      //Button Pressed, Change the color of your Button here. 

     break; 

     case MotionEvent.ACTION_UP: 

     break; 

     case MotionEvent.ACTION_MOVE: 

     break; 

    } 

    return true; 
} 

} 

我希望這有助於。

+0

不工作.... – mSO

+0

好吧,你到底想完成什麼?你爲什麼要通過onDraw方法獲取狀態? –

+0

聚焦時我想改變顏色 – mSO

0

試試這個自定義繪製對象:

class SLD extends StateListDrawable { 
    @Override 
    protected boolean onStateChange(int[] stateSet) { 
     invalidateSelf(); 
     return super.onStateChange(stateSet); 
    } 

    @Override 
    public void draw(Canvas canvas) { 
     int[] states = getState(); 
     Log.d(TAG, "draw " + StateSet.dump(states)); 
     boolean pressed = false; 
     boolean focused = false; 
     for (int i = 0; i < states.length; i++) { 
      int state = states[i]; 
      if (state == android.R.attr.state_pressed) { 
       pressed = true; 
      } 
      if (state == android.R.attr.state_focused) { 
       focused = true; 
      } 
     } 
     if (pressed) { 
      canvas.drawColor(0xffff8800); 
     } else 
     if (focused) { 
      canvas.drawColor(0xffff0000); 
     } else 
     canvas.drawColor(0xffaaaaaa); 
    } 
} 

,並與的onCreate以下測試:

LinearLayout ll = new LinearLayout(this); 
ll.setOrientation(LinearLayout.VERTICAL); 
for (int i = 0; i < 5; i++) { 
    Button b = new Button(this); 
    b.setText("button #" + i); 
    b.setBackgroundDrawable(new SLD()); 
    ll.addView(b); 
} 
setContentView(ll); 
相關問題