网络上关于GridView可拖动的例子已经不少了,包括带动画不带动画的都有一堆,但几乎都是通过继承Android原生控件GridView来扩展的,当然这种实现方式是很容易联想到的,也是最容易实现的。我随便百度了一下,就有一个:http://zhangcb666.blog.163.com/blog/static/4696352920124221043837/,大家可以参考一下,我这里就不赘述了。
今天跟大家分享另外一种方式,通过继承ViewGroup来实现,我们都知道,ViewGroup可以填充很多个View,因此,我觉得可以类似把GridView的每一个Item填充到我们自定义的ViewGroup中,然后监听长按时间,实现拖动的效果,同时加上动画效果,个人感觉比网上其他实现方式更加简洁和美观,唯一的缺点就是:没有setAdapter的函数,添加的item,需要我们手动add到ViewGroup中,如果item不是特别复杂和繁多,个人觉得也不算什么问题。好了,废话不多说,我们先来看看效果图,第一张是静态效果,第二张是拖动时的效果图。
其实代码也是很简单的,总共就两个类:一个自定义控件DragGridView,还有一个使用的例子MainActivity。
我们先来看看DragGridView的代码部分:
[java] view plain copy
- /**
- * 另外一种方式实现动画可拖动item的GridView
- *
- * @author way
- *
- */
- public class DragGridView extends ViewGroup implements
- View.OnClickListener, View.OnLongClickListener {
- // layout vars
- public static float
- protected int colCount, childSize, padding, dpi, scroll = 0;
- protected float lastDelta = 0;
- protected Handler handler = new
- // dragging vars
- protected int dragged = -1, lastX = -1, lastY = -1, lastTarget = -1;
- protected boolean enabled = true, touching = false;
- // anim vars
- public static int animT = 150;
- protected ArrayList<Integer> newPositions = new
- // listeners
- protected
- protected
- private
- /**
- * 拖动item的接口
- */
- public interface
- public abstract void onRearrange(int oldIndex, int
- }
- // CONSTRUCTOR AND HELPERS
- public
- super(context, attrs);
- setListeners();
- handler.removeCallbacks(updateTask);
- 500);
- true);
- new
- ((Activity) context).getWindowManager().getDefaultDisplay()
- .getMetrics(metrics);
- dpi = metrics.densityDpi;
- }
- protected void
- this);
- super.setOnClickListener(this);
- this);
- }
- @Override
- public void
- secondaryOnClickListener = l;
- }
- protected Runnable updateTask = new
- public void
- if (dragged != -1) {
- if (lastY < padding * 3 && scroll > 0)
- 20;
- else if (lastY > getBottom() - getTop() - (padding * 3)
- && scroll < getMaxScroll())
- 20;
- else if (lastDelta != 0
- scroll += lastDelta;
- 9;
- if (Math.abs(lastDelta) < .25)
- 0;
- }
- clampScroll();
- true, getLeft(), getTop(), getRight(), getBottom());
- this, 25);
- }
- };
- @Override
- public void
- super.addView(child);
- 1);
- };
- @Override
- public void removeViewAt(int
- super.removeViewAt(index);
- newPositions.remove(index);
- };
- // LAYOUT
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int
- // compute width of view, in dp
- float
- // determine number of columns, at least 2
- 2;
- int sub = 240;
- 280;
- while (w > 0) {
- colCount++;
- w -= sub;
- 40;
- }
- // determine childSize and padding, in px
- childSize = (r - l) / colCount;
- childSize = Math.round(childSize * childRatio);
- 1);
- for (int i = 0; i < getChildCount(); i++)
- if
- Point xy = getCoorFromIndex(i);
- getChildAt(i).layout(xy.x, xy.y, xy.x + childSize,
- xy.y + childSize);
- }
- }
- @Override
- protected int getChildDrawingOrder(int childCount, int
- if (dragged == -1)
- return
- else if (i == childCount - 1)
- return
- else if
- return i + 1;
- return
- }
- public int getIndexFromCoor(int x, int
- int
- if (col == -1 || row == -1) // touch is between columns or rows
- return -1;
- int
- if
- return -1;
- return
- }
- protected int getColOrRowFromCoor(int
- coor -= padding;
- for (int i = 0; coor > 0; i++) {
- if
- return
- coor -= (childSize + padding);
- }
- return -1;
- }
- protected int getTargetFromCoor(int x, int
- if (getColOrRowFromCoor(y + scroll) == -1) // touch is between rows
- return -1;
- // if (getIndexFromCoor(x, y) != -1) //touch on top of another visual
- // return -1;
- int leftPos = getIndexFromCoor(x - (childSize / 4), y);
- int rightPos = getIndexFromCoor(x + (childSize / 4), y);
- if (leftPos == -1 && rightPos == -1) // touch is in the middle of
- // nowhere
- return -1;
- if (leftPos == rightPos) // touch is in the middle of a visual
- return -1;
- int target = -1;
- if (rightPos > -1)
- target = rightPos;
- else if (leftPos > -1)
- 1;
- if
- return target - 1;
- // Toast.makeText(getContext(), "Target: " + target + ".",
- // Toast.LENGTH_SHORT).show();
- return
- }
- protected Point getCoorFromIndex(int
- int
- int
- return new
- + (childSize + padding) * row - scroll);
- }
- public int
- for (int i = 0; i < getChildCount(); i++)
- if
- return
- return -1;
- }
- // EVENT HANDLERS
- public void
- if
- if (secondaryOnClickListener != null)
- secondaryOnClickListener.onClick(view);
- if (onItemClickListener != null && getLastIndex() != -1)
- null,
- getChildAt(getLastIndex()), getLastIndex(),
- getLastIndex() / colCount);
- }
- }
- public boolean
- if
- return false;
- int
- if (index != -1) {
- dragged = index;
- animateDragged();
- return true;
- }
- return false;
- }
- public boolean
- int
- switch
- case
- true;
- int) event.getX();
- int) event.getY();
- true;
- break;
- case
- int delta = lastY - (int) event.getY();
- if (dragged != -1) {
- // change draw location of dragged visual
- int x = (int) event.getX(), y = (int) event.getY();
- int l = x - (3 * childSize / 4), t = y - (3 * childSize / 4);
- 3 / 2),
- 3 / 2));
- // check for new target hover
- int
- if
- if (target != -1) {
- animateGap(target);
- lastTarget = target;
- }
- }
- else
- scroll += delta;
- clampScroll();
- if (Math.abs(delta) > 2)
- false;
- true, getLeft(), getTop(), getRight(), getBottom());
- }
- int) event.getX();
- int) event.getY();
- lastDelta = delta;
- break;
- case
- if (dragged != -1) {
- View v = getChildAt(dragged);
- if (lastTarget != -1)
- reorderChildren();
- else
- Point xy = getCoorFromIndex(dragged);
- v.layout(xy.x, xy.y, xy.x + childSize, xy.y + childSize);
- }
- v.clearAnimation();
- if (v instanceof
- 255);
- 1;
- 1;
- }
- false;
- break;
- }
- if (dragged != -1)
- return true;
- return false;
- }
- // EVENT HELPERS
- protected void
- View v = getChildAt(dragged);
- int x = getCoorFromIndex(dragged).x + childSize / 2, y = getCoorFromIndex(dragged).y
- 2;
- int l = x - (3 * childSize / 4), t = y - (3 * childSize / 4);
- 3 / 2), t + (childSize * 3 / 2));
- new AnimationSet(true);
- new ScaleAnimation(.667f, 1, .667f, 1,
- 3 / 4, childSize * 3 / 4);
- scale.setDuration(animT);
- new AlphaAnimation(1, .5f);
- alpha.setDuration(animT);
- animSet.addAnimation(scale);
- animSet.addAnimation(alpha);
- true);
- true);
- v.clearAnimation();
- v.startAnimation(animSet);
- }
- protected void animateGap(int
- for (int i = 0; i < getChildCount(); i++) {
- View v = getChildAt(i);
- if
- continue;
- int
- if (dragged < target && i >= dragged + 1
- newPos--;
- else if
- newPos++;
- // animate
- int
- if (newPositions.get(i) != -1)
- oldPos = newPositions.get(i);
- if
- continue;
- Point oldXY = getCoorFromIndex(oldPos);
- Point newXY = getCoorFromIndex(newPos);
- new
- - v.getTop());
- new
- - v.getTop());
- new
- Animation.ABSOLUTE, oldOffset.x, Animation.ABSOLUTE,
- newOffset.x, Animation.ABSOLUTE, oldOffset.y,
- Animation.ABSOLUTE, newOffset.y);
- translate.setDuration(animT);
- true);
- true);
- v.clearAnimation();
- v.startAnimation(translate);
- newPositions.set(i, newPos);
- }
- }
- protected void
- // FIGURE OUT HOW TO REORDER CHILDREN WITHOUT REMOVING THEM ALL AND
- // RECONSTRUCTING THE LIST!!!
- if (onRearrangeListener != null)
- onRearrangeListener.onRearrange(dragged, lastTarget);
- new
- for (int i = 0; i < getChildCount(); i++) {
- getChildAt(i).clearAnimation();
- children.add(getChildAt(i));
- }
- removeAllViews();
- while
- if (lastTarget == children.size()) // dragged and dropped to the
- // right of the last element
- {
- children.add(children.remove(dragged));
- dragged = lastTarget;
- else if (dragged < lastTarget) // shift to the right
- {
- 1);
- dragged++;
- else if (dragged > lastTarget) // shift to the left
- {
- 1);
- dragged--;
- }
- for (int i = 0; i < children.size(); i++) {
- 1);
- addView(children.get(i));
- }
- true, getLeft(), getTop(), getRight(), getBottom());
- }
- public void
- 0;
- }
- public void
- scroll = Integer.MAX_VALUE;
- clampScroll();
- }
- protected void
- int stretch = 3, overreach = getHeight() / 2;
- int
- 0);
- if
- scroll = -overreach;
- 0;
- else if
- scroll = max + overreach;
- 0;
- else if (scroll < 0) {
- if
- 0;
- else if
- scroll -= scroll / stretch;
- else if
- if
- scroll = max;
- else if
- scroll += (max - scroll) / stretch;
- }
- }
- protected int
- int rowCount = (int) Math.ceil((double) getChildCount() / colCount), max = rowCount
- 1) * padding - getHeight();
- return
- }
- public int
- return
- }
- // OTHER METHODS
- public void
- this.onRearrangeListener = l;
- }
- public void
- this.onItemClickListener = l;
- }
- }
然后是在布局文件中声明:main.xml
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- <com.way.view.DragGridView
- android:id="@+id/vgv"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true" />
- <Button
- android:id="@+id/add_item_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:text="@string/button1Text" />
- <Button
- android:id="@+id/view_poem_item"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_toRightOf="@+id/add_item_btn"
- android:text="@string/button2Text" />
- </RelativeLayout>
最后就可以直接在代码中调用了MainActivity:
[java] view plain copy
- /**
- * MainActivity
- *
- * @author way
- *
- */
- public class MainActivity extends
- static Random random = new
- static String[] words = "我 是 一 只 大 笨 猪".split(" ");
- DragGridView mDragGridView;
- Button mAddBtn, mViewBtn;
- new
- @Override
- public void
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mDragGridView = ((DragGridView) findViewById(R.id.vgv));
- mAddBtn = ((Button) findViewById(R.id.add_item_btn));
- mViewBtn = ((Button) findViewById(R.id.view_poem_item));
- setListeners();
- }
- private void
- new
- public void onRearrange(int oldIndex, int
- String word = poem.remove(oldIndex);
- if
- poem.add(newIndex, word);
- else
- poem.add(newIndex, word);
- }
- });
- new
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int
- long
- mDragGridView.removeViewAt(arg2);
- poem.remove(arg2);
- }
- });
- new
- public void
- String word = words[random.nextInt(words.length)];
- new ImageView(MainActivity.this);
- view.setImageBitmap(getThumb(word));
- mDragGridView.addView(view);
- poem.add(word);
- }
- });
- new
- public void
- "";
- for
- " ";
- new AlertDialog.Builder(MainActivity.this).setTitle("这是你选择的")
- .setMessage(finishedPoem).show();
- }
- });
- }
- private
- 150, 150, Bitmap.Config.RGB_565);
- new
- new
- 128), random.nextInt(128),
- 128)));
- 24);
- paint.setFlags(Paint.ANTI_ALIAS_FLAG);
- new Rect(0, 0, 150, 150), paint);
- paint.setColor(Color.WHITE);
- paint.setTextAlign(Paint.Align.CENTER);
- 75, 75, paint);
- return
- }
- }