android imageview 拖移 代码
public class MainActivity extends AppCompatActivity {
private android.widget.ImageView image;
final String msg = "drag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.image = (ImageView) findViewById(R.id.image);
image.setOnLongClickListener(new View.OnLongClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData dragData = new ClipData("",
mimeTypes, item);
// Instantiates the drag shadow builder.
View.DragShadowBuilder myShadow = new View.DragShadowBuilder(image);
// Starts the drag
v.startDragAndDrop(dragData, // the data to be dragged
myShadow, // the drag shadow builder
null, // no need to use local data
0 // flags (not currently used, set to 0)
);
return true;
}
});
image.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View view, DragEvent dragEvent) {
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) view.getLayoutParams();
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
layoutParams = (ConstraintLayout.LayoutParams)
view.getLayoutParams();
Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
// Do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
int x_cord = (int) dragEvent.getX();
int y_cord = (int) dragEvent.getY();
break;
case DragEvent.ACTION_DRAG_EXITED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
x_cord = (int) dragEvent.getX();
y_cord = (int) dragEvent.getY();
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
view.setLayoutParams(layoutParams);
break;
case DragEvent.ACTION_DRAG_LOCATION:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
x_cord = (int) dragEvent.getX();
y_cord = (int) dragEvent.getY();
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
// Do nothing
break;
case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");
// Do nothing
break;
default:
break;
}
return true;
}
});
}
}
你尚未登录,无法进行回复。