<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.xingyi.moveviewwithtouch.MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="40dp" android:layout_height="40dp" android:background="@android:color/black"/> </RelativeLayout>
package com.xingyi.moveviewwithtouch;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
RelativeLayout relativeLayout;
int heightRL,widthRL;
int halfHeight,halfWidth;
boolean first=true;
private int widthImg;
private int heightImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
//初始化视图
private void initView() {
imageView = (ImageView) findViewById(R.id.imageView);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//获取滑动瞬间位置和点击瞬间位置,并移动imageview
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_MOVE:
moveView(imageView, motionEvent.getX(), motionEvent.getY());
break;
case MotionEvent.ACTION_DOWN:
getWidthAndHeight();
moveView(imageView, motionEvent.getX(), motionEvent.getY());
break;
default:
break;
}
return true;
}
});
}
//因为不能在初始化视图时获得长宽,而每次计算一次长宽又影响性能
private void getWidthAndHeight(){
if(first){
widthRL=relativeLayout.getWidth();
heightRL=relativeLayout.getHeight();
widthImg=imageView.getWidth();
heightImg=imageView.getHeight();
halfWidth = imageView.getWidth() / 2;//imageView宽度的一半
halfHeight = imageView.getHeight() / 2;//imageView高度的一半
first=false;
}
}
//滑动瞬间,将x和y分别作imageView的中心点到relativeLayout最左和顶端距离
private void moveView(View view, float x, float y) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
//设置水平位置
if (x < halfWidth) {//左边缘
params.leftMargin = 0;//设置imageview到左端距离为0
} else if (x > widthRL- halfWidth) {
params.leftMargin = widthRL-widthImg;//设置imageview左端到左端端距离(params.rightMargin的性能非常糟糕)
} else {
params.leftMargin = (int) (x - halfWidth);//imageview左端到relativelayout左端距离
}
//设置竖直位置
if (y < halfHeight) {
params.topMargin = 0;
} else if (y > heightRL - halfHeight) {
params.topMargin = heightRL-widthImg;//params.bottomMargin的性能非常糟糕
} else {
params.topMargin = (int) (y - halfHeight);
}
view.setLayoutParams(params);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有