我在網上搜索了一個簡單的解決方案,以自由移動ImageView
。我終於找到了一些代碼,產生完美的結果:Android移動ImageView
public class MainActivity extends Activity implements View.OnTouchListener {
private int _xDelta;
private int _yDelta;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView j = (ImageView)findViewById(R.id.j);
j.setOnTouchListener(this);
}
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
ImageView j = (ImageView)findViewById(R.id.j);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
_xDelta = (int) (X - j.getTranslationX());
_yDelta = (int) (Y - j.getTranslationY());
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
j.setTranslationX(X - _xDelta);
j.setTranslationY(Y - _yDelta);
break;
}
return true;
}}
因爲我真的不知道我的代碼是如何工作的,我想看看是否有更好的解決方案。