我有一个网格视图,我设置了一个包含图像视图数组列表的适配器。我想从网格视图中拖动一个项目并将其放入另一个布局。我面临的问题是如何将触摸侦听器设置为单个网格视图项,以便我可以将其放入目标中。如果我在网格视图中设置ontouchlistener,它将选择整个网格视图而不是单个项目。请帮我............... 我试过这段代码:
gridview.setOnItemClickListener(new MyOnItemClickListener());
gridview.setOnDragListener(new MyOnDragListener());
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
return true;
} else {
return false;
}
}
final class MyOnDragListener implements OnDragListener{
Drawable enterShape = getResources().getDrawable(R.drawable.shape_droptarget);
Drawable historyDrawer;
@Override
public boolean onDrag(View v, DragEvent event) {
LocalLogger.LOGGER.info("Under on drag listener");
switch(event.getAction()){
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
historyDrawer=v.getBackground();
v.setBackground(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackground(historyDrawer);
break;
case DragEvent.ACTION_DROP:
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
}
return false;
}
}
答案 0 :(得分:1)
使用OnItemLongClickListener查找长按的孩子。
答案 1 :(得分:1)
将其添加到网格中,就像这样 -
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
return true;
}
});
答案 2 :(得分:0)
由于您只在触控侦听器上使用ACTION_DOWN
,因此您可以使用onItemClickListener或onItemLongClickListener进行拖动。
grid.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int pos, long id) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
v);
// start dragging the item touched
v.startDrag(data, shadowBuilder, v, 0);
return false;
}
});
答案 3 :(得分:0)
我接下来解决了这个问题:
gridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float currentXPosition = motionEvent.getX();
float currentYPosition = motionEvent.getY();
int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);
View v = gridView.getChildAt(position);
ClipData.Item item = new ClipData.Item("" + position); // here you send any data you want, I sent position
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_HTML};
ClipData data = new ClipData("" + position, mimeTypes, item);
View.DragShadowBuilder shadow = new View.DragShadowBuilder(v);
view.startDrag(data, shadow, null, 0);
}