嗨我创建了一个项目,我想在屏幕上移动图像,我已经通过下面的代码成功完成了
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="matrix"
android:src="@drawable/img_lock_normal" />
</RelativeLayout>
java代码是
public class MainActivity extends Activity {
int windowwidth;
int windowheight;
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private LayoutParams layoutParams;
private int mode = NONE;
private float[] lastEvent = null;
// remember some things for zooming
private PointF start = new PointF();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();
final ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
// drag(event, v);
return true;
}
});
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) img
.getLayoutParams();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
lastEvent = null;
break;
case MotionEvent.ACTION_UP:
layoutParams.leftMargin = windowwidth / 2 - v.getWidth()
/ 2;
layoutParams.topMargin = windowheight - v.getHeight();
img.setLayoutParams(layoutParams);
break;
case MotionEvent.ACTION_MOVE:
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
if (x_cord > windowwidth) {
x_cord = windowwidth;
}
if (y_cord > windowheight) {
y_cord = windowheight;
}
layoutParams.leftMargin = x_cord - v.getWidth() / 2;
layoutParams.topMargin = y_cord - v.getHeight();
img.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
}
图像跟在我的手指上它工作正常但是当我将图像拖到底部时它无法正常工作我无法正确描述所以我有共享视频请看它
Problem with drag image on view ---Youtube
请有人帮助我