我做了一个拖放GridView。除了第一次拖放之外,一切都完美无缺。我找不到它只发生第一次的原因。
我第一次将一个项目拖到 gridview 中的其他项目上时,项目的 imageview 源丢失了。当我放下它时,来源将被修复。之后,一切都会正常工作。知道如何解决这个问题或奇怪行为的原因吗?
这是我的 touchListener,它将处理拖放:
mGridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
GridView parent = (GridView) v;
int x = (int) event.getX();
int y = (int) event.getY();
int position = parent.pointToPosition(x, y);
if (position > AdapterView.INVALID_POSITION) {
int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
View curr = parent.getChildAt(i);
curr.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
boolean result = true;
int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_LOCATION:
break;
case DragEvent.ACTION_DRAG_ENTERED:
setBlueFilterOnImageView((ImageView) v, getActivity());
break;
case DragEvent.ACTION_DRAG_EXITED:
clearColorFilterOnImageView((ImageView) v);
break;
case DragEvent.ACTION_DROP:
if (event.getLocalState() == v) {
result = false;
} else {
View droped = (View) event.getLocalState();
View target = v;
app.myProfile().removeProfilePhotoAtIndex(((DragGridItemHolder) droped.getTag()).position);
app.myProfile().insertProfilePhoto(((DragGridItemHolder) droped.getTag()).id, ((DragGridItemHolder) target.getTag()).position);
mAdapter.notifyDataSetChanged();
}
break;
case DragEvent.ACTION_DRAG_ENDED:
clearColorFilterOnImageView((ImageView) v);
break;
default:
result = false;
break;
}
return result;
}
});
}
int relativePosition = position - parent.getFirstVisiblePosition();
View target = (View) parent.getChildAt(relativePosition);
DragGridItemHolder holder = (DragGridItemHolder) target.getTag();
String text = holder.id;
ClipData data = ClipData.newPlainText("DragData", text);
target.startDrag(data, new View.DragShadowBuilder(target), target, 0);
}
}
return false;
}
});
编辑
public static void setBlueFilterOnImageView(ImageView imageView, Context context){
PorterDuffColorFilter blueFilter = new PorterDuffColorFilter(
context.getResources().getColor(R.color.grid_state_focused),
PorterDuff.Mode.SRC_ATOP);
imageView.setColorFilter(blueFilter);
imageView.setBackgroundColor(context.getResources().getColor(
R.color.grid_state_pressed));
}