android 控件拖动

第一篇简书的文章,记录下我的学习情况吧,目前想学习下android的拖拽的实现,因为支付宝之前的首页是支持拖动的,而且实现非常好看,我就想实现支付宝的控件拖动,后来支付宝更新之后改成添加了,这个demo我也实现了,所以现在学习一下android的拖拽,现在网上找个例子。

Android控件拖动 - 卡尔 - 博客频道 - CSDN.NET

public classDraftDemoextendsAppCompatActivityimplementsView.OnTouchListener {

ImageView image;

int X,Y;

int screenWidth,screenHeight;

ActionBar actionbar;

@Override

protected void onCreate(@NullableBundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.draft);

image= (ImageView) findViewById(R.id.image);

if(image!=null) {

image.setOnTouchListener(this);

}

actionbar= getSupportActionBar();

Display dis =this.getWindowManager().getDefaultDisplay();

screenWidth= dis.getWidth();

screenHeight= dis.getHeight();

}

@Override

public booleanonTouch(View v,MotionEvent event) {

switch(event.getAction()) {

caseMotionEvent.ACTION_DOWN:

X= (int) event.getRawX();

Y= (int) event.getRawY();

break;

caseMotionEvent.ACTION_MOVE:

int dx = (int) event.getRawX() -X;

int dy = (int) event.getRawY() -Y;

int top = v.getTop() + dy;

int left = v.getLeft() + dx;

if(top <=0) {

top =0;

}

if(actionbar!=null){//判断是否超出屏幕范围

if(top >=screenHeight-image.getHeight()-actionbar.getHeight()-getStatusBarHeight()) {

top =screenHeight-image.getHeight()-actionbar.getHeight()-getStatusBarHeight();

}

}else{

if(top >=screenHeight-image.getHeight()-getStatusBarHeight()) {

top =screenHeight-image.getHeight()-getStatusBarHeight();

}

}

if(left >=screenWidth-image.getWidth()) {

left =screenWidth-image.getWidth();

}

if(left <=0) {

left =0;

}

v.layout(left,top,left +image.getWidth(),top +image.getHeight());

X= (int) event.getRawX();

Y= (int) event.getRawY();

break;

caseMotionEvent.ACTION_UP:

break;

}

return false;

}

private intgetStatusBarHeight() {

Class c =null;

Object obj =null;

Field field =null;

intx =0,sbar =0;

try{

c = Class.forName("com.android.internal.R$dimen");

obj = c.newInstance();

field = c.getField("status_bar_height");

x = Integer.parseInt(field.get(obj).toString());

sbar =this.getResources().getDimensionPixelSize(x);

}catch(Exception e1) {

e1.printStackTrace();

}

returnsbar;

}

上面这段代码是根据链接的源代码修改得来,源代码没有解决有actionbar时的高度检测不正确的问题,intgetStatusBarHeight()该函数是返回手机状态栏的高度,加上actionbar完美解决。

解释:getTop();是获取子View左上角距父View顶部的距离,getLeft();是获取子View左上角距父View左侧的距离;event.getX();event.getY();是触摸点相对于其所在组件坐标系的坐标event.getRawX();event.getRawY();是触摸点相对于屏幕默认坐标系的坐标。详情请看这边

自定义View基础-坐标系

这篇就简单说明这些。至于事件分发以后再更。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容