我正在做一个项目。在我需要拖动布局的地方,我设法移动(拖动)布局,但是当我释放触摸时,它并没有到达原来的位置。
请任何人告诉我应该在 MotionEvent.ACTION_UP 中做什么,以便我可以将布局恢复到其原始位置。
以下是我的代码。
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class HomeActivity extends Activity implements OnTouchListener {
RelativeLayout _view;
RelativeLayout _view1;
// TextView _view;
ViewGroup _root;
private int _xDelta;
RelativeLayout.LayoutParams lParams;
RelativeLayout.LayoutParams mainlParams;
private int _yDelta;
// private int X1, Y1, width;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_root = (ViewGroup) findViewById(R.id.root);
_view = (RelativeLayout) findViewById(R.id.relativeLayout);
_view.setOnTouchListener(this);
lParams = (RelativeLayout.LayoutParams) _view.getLayoutParams();
mainlParams = (RelativeLayout.LayoutParams) _view.getLayoutParams();
// _root.addView(_view1);
}
public boolean onTouch(View view, MotionEvent event) {
int X = (int) event.getRawX();
int Y = (int) event.getRawY();
RelativeLayout.LayoutParams layoutParams;
lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
Log.e("", "inside ACTION_DOWN");
lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
Log.e("", "inside ACTION_UP");
if ((X - _xDelta) < -150) {
_root.removeView(_view);
} else {
view.setLayoutParams(mainlParams);
}
break;
case MotionEvent.ACTION_MOVE:
Log.e("", "inside ACTION_MOVE");
layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
view.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
}