我在我的按钮类中覆盖了onDraw。
我如何知道onDraw里面按下了按钮?
答案 0 :(得分: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;
}
}
我希望这会有所帮助。
答案 1 :(得分:0)
尝试这个自定义Drawable:
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);