您的位置:首页 > 其它

自定义可以按键控制自由移动的View

2016-07-12 15:35 381 查看
主要通过监听按键,设置view位置,重新绘制,实现view的自由移动

代码比较简单 (如下):

public class MoveView extends View {
private static final int WIDTH = 40;
private static final String TAG = "MoveView";
private Rect mRect;
private Paint mPaint;
private int mColor;
private float mWidth;

public MoveView(Context context) {
super(context);
init();
}

public MoveView(Context context, AttributeSet attrs) {
super(context, attrs);

TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MoveView, 0, 0);

try {
mColor = typedArray.getColor(R.styleable.MoveView_border_color, 0xE27B6A);
mWidth = typedArray.getDimension(R.styleable.MoveView_border_width, 2);

} finally {

typedArray.recycle();
}

init();
}

private void init() {

this.setFocusable(true);   //获取焦点
this.setFocusableInTouchMode(true);
this.setClickable(true);

mRect = new Rect(0, 0, WIDTH, WIDTH);   //画一个矩形
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);  //画笔
mPaint.setColor(Color.RED);

}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(mRect, mPaint);    //draw
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {   //监听按键

/*
* ok    23
* right 22
* left  21
* top   19
* below 20
* */

if (keyCode == 22) {  //右移
mRect.left += WIDTH;
mRect.right += WIDTH;

} else if (keyCode == 21) { //左移
mRect.left = mRect.left - WIDTH;
mRect.right = mRect.right - WIDTH;
} else if (keyCode == 20) {  //下移

mRect.top += WIDTH;
mRect.bottom += WIDTH;

} else if (keyCode == 19) {  //上移
mRect.top -= WIDTH;
mRect.bottom -= WIDTH;
}

invalidate(mRect);   //重新绘制矩形的

Log.d(TAG, "key code" + keyCode);
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息