我已经为拖动实现苦苦挣扎了将近一个星期。我从这里尝试了很多教程和示例代码,但到目前为止我尝试的每个实现都有缺陷。这是我发现的最简单的一个,下面这个几乎可以工作。这里的问题是这个问题是,一旦我触摸图像,它就会移动到触摸点下方。它可以四处拖动,但有点悬在触摸点下方几厘米处。谢谢
package com.example.imagedrag;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
public class DragImage extends Activity {
int windowwidth;
int windowheight;
private LayoutParams layoutParams;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();
final ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) img
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
img.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
}
}
我的 XML 如下:
<LinearLayout 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:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="126dp"
android:layout_marginTop="168dp"
android:src="@drawable/c1" />
</LinearLayout>
最佳答案
如何替换
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
与
layoutParams.leftMargin = x_cord-img.getWidth()/2;
layoutParams.topMargin = y_cord-img.getHeight()/2;
,我认为这应该可以解决您的问题。 希望我有所帮助:)
关于Android:拖动图像:图像在触摸点下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20422254/