要求:
1.通过手指移动来拖动图片
2.控制图片不能超出屏幕显示区域
技术点:
1.MotionEvent处理
2.对View进行动态定位(layout)
activity_main.xml:
代码如下 | 复制代码 |
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> android:id="@+id/iv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/test"/> |
MainActivity:
代码如下 | 复制代码 |
publicclassMainActivityextendsActivityimplementsOnTouchListener { privateImageView iv_main; privateRelativeLayout parentView; @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_main = (ImageView) findViewById(R.id.iv_main); parentView = (RelativeLayout) iv_main.getParent(); /* int right = parentView.getRight(); //0 int bottom = parentView.getBottom(); //0 Toast.makeText(this, right+"---"+bottom, 1).show(); */ //设置touch监听 iv_main.setOnTouchListener(this); } privateintlastX; privateintlastY; privateintmaxRight; privateintmaxBottom; @Override publicbooleanonTouch(View v, MotionEvent event) { //得到事件的坐标 inteventX = (int) event.getRawX(); inteventY = (int) event.getRawY(); switch(event.getAction()) { caseMotionEvent.ACTION_DOWN: //得到父视图的right/bottom if(maxRight==0) {//保证只赋一次值 maxRight = parentView.getRight(); maxBottom = parentView.getBottom(); } //第一次记录lastX/lastY lastX =eventX; lastY = eventY; break; caseMotionEvent.ACTION_MOVE: //计算事件的偏移 intdx = eventX-lastX; intdy = eventY-lastY; //根据事件的偏移来移动imageView intleft = iv_main.getLeft()+dx; inttop = iv_main.getTop()+dy; intright = iv_main.getRight()+dx; intbottom = iv_main.getBottom()+dy; //限制left >=0 if(left<0) { right += -left; left =0; } //限制top if(top<0) { bottom += -top; top =0; } //限制right <=maxRight if(right>maxRight) { left -= right-maxRight; right = maxRight; } //限制bottom <=maxBottom if(bottom>maxBottom) { top -= bottom-maxBottom; bottom = maxBottom; } iv_main.layout(left, top, right, bottom); //再次记录lastX/lastY lastX = eventX; lastY = eventY; break; default: break; } returntrue;//所有的motionEvent都交给imageView处理 } } |
凡尔赛法环免广告版 最新版v1.69.1
下载天煞异种 安卓版v1.0.21
下载十三月 (Undecember)最新官方中文版v3.26.0200
下载我不是废柴无限99999钻999999金币游戏 不减反增版v1.2.16
下载我的女友是声优免广告 安卓版v1
我的女友是声优免广告是一款非常好玩的模拟经营类手游,玩家在游
石器帝国去广告版 v8
石器帝国免广告版是游戏的破解版本,在该版本中为玩家去除了广告
校园恋爱模拟器真人版去广告版 v0.0.7
校园恋爱模拟器真人版免广告版是游戏的破解版本,在该版本中为玩
教练我要开球馆内置菜单修改器 安卓版v1.5.4
教练我要开球馆内购版是一款模拟经营类游戏,玩家们将在游戏中创
我的游轮无限砖石 安卓版v1.7.0
我的游轮无限金币钻石版是一款模拟经营类游戏,你将成为一艘游轮