我已經創建了一個簡單的拖放應用程序在android.But現在我想要移動視圖在x軸上而不接觸視圖本身。視圖應該從任何地方移動用戶觸摸屏幕的屏幕。我可以如何實現這一效果。通過觸摸下方的對象拖動視圖,並相應地移動
目前我使用的是拖放操作的教程。我在父視圖中應用了OnTouchListner。但是我認爲這不是一個好主意。請問任何人都可以爲我提供正確的方法。
這裏是我的代碼
rel.setOnTouchListener(this);
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
dX = v.getX() - event.getRawX();
dY = v.getY() - event.getRawY();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
v.setY(event.getRawY() + dY);
v.setX(event.getRawX() + dX);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
if (lastAction == MotionEvent.ACTION_DOWN)
Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
break;
default:
return false;
}
return true;
}
和我的XML代碼
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rel"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/ball"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ball" />
</RelativeLayout>
你可以從案例MotionEvent.ACTION_MOVE中移除'v.setY(event.getRawY()+ dY)'行嗎? –
@MayurRaval是的,它現在只會在x軸上移動 – AbhayBohra