自定义可以按键控制自由移动的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; } }
相关文章推荐
- 在 Linux 中如何移动文件
- PowerShell移动目录中指定文件的方法(非全部文件)
- 鼠标触发移动的分层菜单 层菜单moveMenu
- C#控制键盘按键的常用方法
- 基于Android实现随手指移动的ImageView
- php实现复制移动文件的方法
- javascript 广告移动特效的实现代码
- javascript实现图片跟随鼠标移动效果的方法
- JavaScript Select和Option列表元素上下左右移动
- JavaScript代码实现左右上下自动晃动自动移动
- JS实现网页游戏中滑块响应鼠标点击移动效果
- JS+CSS实现分类动态选择及移动功能效果代码
- 详解jQuery移动页面开发中的ui-grid网格布局使用
- jquery移动点击的项目到列表最顶端的方法
- 基于jquery实现select选择框内容左右移动添加删除代码分享
- jquery实现select选择框内容左右移动代码分享
- 使用jQuery mobile库检测url绝对地址和相对地址的方法
- jQuery移动web开发之页面跳转和加载外部页面的实现
- JQuery移动页面开发之屏幕方向改变与滚屏的实现
- 浅析jQuery Mobile的初始化事件