Tuesday, February 14, 2012

Moving elements in a ListView


»How do I move elements i a ListView?
I see this question asked a lot recently, so let me just try to explain some ways you can archive this, and hopefully I'll get asked that question a lot less in the near future hah.

Basically there are two good ways I've found out to do it, one way is to use the nicely custom made ListView called cwac-touchlist partially coded by CommonsWare from Stackoverflow, partially because he's taken the source code for the custom ListView in the default Android music player worked a little further on it, and bundled it in a nice, easy to use way. It can still be a little troublesome to get it working, and will most likely require a  lot of little tweaks to make it fit just about right in your own project.

There is already a good explanation in the before mentioned link to get it working in your project, so I won't use time to basically just say what he has already written.
--

Now, if you like me could use a more lightweight, less feature rich, but more simple, way to archive moving of elements in a ListView, read on. My version doesn't use drag and drop, however, it is possible to do something alike, but it requires a little extra work.

To put into words what I am really doing, I am simply swapping two elements in the ListView, and then put on a nice animation on each of the views. It sounds simple enough, and it also is.

With all the fat removed it basically comes down to these three parts
  • View.onTouch() handler
  • swapViews() method
  • swapElements() method
In my View.getView(), where the View is generated, I tie an onTouch() handler on each of my slide views (eg. ivSlide), figure out which direction the user´s finger is moving, and set the position for the element which is about to get swapped. Then I find my swapView for the swapPosition, and call swapViews() with the view I pressed, and the swapView.

Everything that happenes in swapView() is simply where the animation of the two views are handled, and when the animations are finished, swapElements() gets called with the positions of the two elements getting swapped.

⇾ The full source code can be found here

⇾ And the more interesting part would be here

1 comment:

  1. This is one of the nice post.Your blog information is really unique compare with other post.Great work.

    ReplyDelete