我想在拖动时实现一个可移动的imageView.拖动工作正常.但是,当我拖动到最后时,imageView离开了屏幕.我如何才能使imageview的可移动对象仅在屏幕内部?

这是我的OnTouch listerner:

public boolean onTouch(View view, MotionEvent event) {

switch (event.getActionMasked()) {

case MotionEvent.ACTION_DOWN:

dX = view.getX() - event.getRawX();

dY = view.getY() - event.getRawY();

lastAction = MotionEvent.ACTION_DOWN;

break;

case MotionEvent.ACTION_MOVE:

view.setY(event.getRawY() + dY);

view.setX(event.getRawX() + dX);

lastAction = MotionEvent.ACTION_MOVE;

break;

case MotionEvent.ACTION_UP:

if (lastAction == MotionEvent.ACTION_DOWN)

Toast.makeText(DraggableView.this, "Clicked!", Toast.LENGTH_SHORT).show();

break;

default:

return false;

}

return true;

}

这是我的布局.布局包含一个滚动视图及其子级,以及要拖动的imageview.

android:layout_width="match_parent"

android:layout_height="match_parent" >

android:layout_width="match_parent"

android:layout_height="match_parent"

android:clickable="true" >

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:layout_width="match_parent"

android:layout_height="400dp"

android:background="#ff0000"

android:gravity="center"

android:text="View 1"

android:textColor="#000"

android:textSize="100dp" />

android:layout_width="match_parent"

android:layout_height="400dp"

android:background="#00ff00"

android:text="View 2"

android:textColor="#000"

android:textSize="100dp" />

android:id="@+id/draggable_view"

android:layout_width="100dp"

android:layout_height="100dp"

android:layout_gravity="bottom|right"

android:layout_marginBottom="20dp"

android:layout_marginEnd="20dp"

android:background="@drawable/icon" />

解决方法:

在花费更多时间后,终于找到最佳解决方案.

将我的OnTouch listerner部分修改为:

DisplayMetrics displaymetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

screenHight = displaymetrics.heightPixels;

screenWidth = displaymetrics.widthPixels;

@SuppressLint("NewApi") @Override

public boolean onTouch(View view, MotionEvent event) {

float newX, newY;

switch (event.getActionMasked()) {

case MotionEvent.ACTION_DOWN:

dX = view.getX() - event.getRawX();

dY = view.getY() - event.getRawY();

lastAction = MotionEvent.ACTION_DOWN;

break;

case MotionEvent.ACTION_MOVE:

newX = event.getRawX() + dX;

newY = event.getRawY() + dY;

// check if the view out of screen

if ((newX <= 0 || newX >= screenWidth-view.getWidth()) || (newY <= 0 || newY >= screenHight-view.getHeight()))

{

lastAction = MotionEvent.ACTION_MOVE;

break;

}

view.setX(newX);

view.setY(newY);

lastAction = MotionEvent.ACTION_MOVE;

break;

case MotionEvent.ACTION_UP:

if (lastAction == MotionEvent.ACTION_DOWN)

Toast.makeText(DraggableView.this, "Clicked!", Toast.LENGTH_SHORT).show();

break;

default:

return false;

}

return true;

}

它工作正常:)

标签:drag,android,ontouchlistener

来源: https://codeday.me/bug/20191012/1900930.html

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐