Android can drag and drop item Listview--draglistvie
Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-size:32px">This blog original, reproduced please indicate the original source: http://blog.csdn.net/sql26/article/details/52252644</span></p></p><p><p></p></p><p><p><span style="font-size:32px">1. overview</span></p></p><p><p><span style="font-size:18px">In the development of <span style="font-family:Calibri">Android</span> <span style="font-family:宋体">project, the need to drag and drop the item in the ListView reorder, online to see some of the posts do a good job, is the code is not open source only write the idea, or the code is not commented, it is better to write A. </span></span></p></p><p><p></p></p><p><p><span style="font-size:32px">2.<span style="font-family:宋体">:</span></span></p></p><p><p><br></p></p><p><p><br></p></p><p><p><span style="font-size:32px">3. Principle <span style="font-family:宋体">:</span></span></p></p><p><p><span style="font-size:18px">1. In the touch event, the Pointtoposition (x, Y) method of the ListView gets the position of the item currently clicked;</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">2. According to the current click of x, y to determine whether the point is the drag trigger button;</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">3. Get the clicked entry view, Itemview = Listview.getchildat (dragendposition-getfirstvisibleposition ());</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">4. Pass Itemview.setdrawingcacheenabled (true); Bitmap.createbitmap (itemview.getdrawingcache ()) Copies the current view to bigtmap;</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">5. Through the WindowManager to show this bitmap, you can use Windowparams = Windowmanager.layoutparams (); Windowmanager.addview (imageView, windowparams); To set the location of the itemview, the size;</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">6. Change the Y value of windowparams in real time in the sliding event Motionevent.action_move in ontouchevent, and update the View windowmanager.updateviewlayout ( dragimageview, windowparams);</span></p></p><p><p><br></p></p><p><p><span style="font-size:18px">7. Real-time switching of data adjacent to 2 item in the movement;</span></p></p><p><p><br></p></p><span style="font-size:18px"><span style="font-size:18px">8. Monitor the motionevent.action_up behavior in the touch event, and call Windowmanager.removeview (view View) to destroy the created hover view for Drag-and-drop signals, and for the 7th step, The data of the start dragged item has been moved to the current position, and the effect looks like it was dragged over;</span></span><p align="justify"><p align="justify"><span style="font-size:18px">Note: instead of actually switching the view of the <span style="font-family:Calibri">item</span> <span style="font-family:宋体">, it transfers their data, and the hover</span> <span style="font-family:Calibri">view</span> <span style="font-family:宋体">is just a form of interaction. Exchange of data in process, similar to bubble sort</span></span></p></p><p align="justify"><p align="justify"><span style="font-family:宋体"></span></p></p><br><p><p><span style="font-size:32px">4. Code</span></p></p><p><p><span style="font-size:18px">Draglistview:</span></p></p><p><p></p></p><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_1_840999" name="code" class="java">Package Com.lunge.dragablelistview;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.color;import Android.util.attributeset;import Android.util.log;import android.view.Gravity; Import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.view.windowmanager;import Android.widget.adapterview;import Android.widget.imageview;import android.widget.listview;/** * Created by Lunger on 8/17 11:21 */public class Draglistview extends ListView {priva Te WindowManager Windowmanager;//windows control class private Windowmanager.layoutparams windowparams;//parameters for controlling the display of drag items Priv Ate ImageView dragimageview;//dragged items (item), is actually a ImageView private int Dragbeginposition;//finger Drag item original position private int dragendposition;//the position of the current drag item in the list when you click Ready to Drag. private int dragpoint;//position in the current data item private int dragyoffset;//the Current view and screen distance (only used in the y direction) private int upscrollbounce;// When dragging, start scrolling up the bounds of private int downscrollbounce;//draggedAt the time, start scrolling down the border private final static int step = 1;//ListView sliding pace. private int current_step;//the Current Pace. private int Temchangid;//temporary Interchange ID private boolean islock;//is locked. Private Mydraglistener mmydraglistener; /** * @param islock drag function switch, true to off */public void Setlock (boolean islock) {this.islock = islock; } public Draglistview (context context, attributeset attrs) {super (context, attrs); }/*** * Touch Event intercept here I intercept accordingly, */@Override public boolean onintercepttouchevent (motionevent ev) { Press if (ev.getaction () = = Motionevent.action_down &&!islock) {int x = (int) Ev.getx ();//get Relative to the X coordinate of the listview int y = (int) ev.gety ();//gets The corresponding y-coordinate with the listview temchangid = Dragbeginposition = Dragen dposition = pointtoposition (x, y); Invalid do not process if (dragendposition = = Adapterview.invalid_position) {return super.onintercepttouche Vent (ev); } Gets the item view of the current location (visible State) viewgroup itemview = (viewgroup) Getchildat (dragendposition- Getfirstvisibleposition ()); The dragpoint is actually the height you click in the specified Item. Dragpoint = Y-itemview.gettop (); This value is fixed: in fact, it is the distance from the top of the screen (typically the title bar + status Bar) of the ListView Control. Dragyoffset = (int) (ev.getrawy ()-y); Get a draggable icon View dragger = Itemview.findviewbyid (r.id.iv_move); The x-coordinate of the click is greater than the x-coordinate of the move button, as if the iv_move triggered the move if (dragger! = null && x > Dragger.getleft ()) {//if you want to click on the item Meaning position can be dragged, the x > Dragger.getleft () limit to remove the line upscrollbounce = GetHeight ()/3;//to Get up the edge of scrolling, about the control of 1/3 Downscrollbounce = getheight () * 2/3;//gets the margin of scroll down, approximately 2/3 itemview.setbackgroundcolor for the control (color.par Secolor ("#a35151")); itemview.setdrawingcacheenabled (true);//open Cache. Bitmap BM = Bitmap.createbitmap (itemview.getdrawingcache ());//create A new BITMA based on the cacheThe P object is the object you are dragging to StartDrag (bm, y);//initialize image} return false; } return super.onintercepttouchevent (ev); /** * Touch Event Processing */@Override public boolean ontouchevent (motionevent ev) {//item view is not empty and gets the drag POSITION valid if (dragimageview! = null && dragendposition! = invalid_position &&!islo Ck) {int action = ev.getaction (); Switch (action) {case MotionEvent.ACTION_UP:int upy = (int) ev.gety (); Stopdrag (); OnDrop (upy); Break Case MotionEvent.ACTION_MOVE:int Movey = (int) ev.gety (); Ondrag (movey); Break Case MotionEvent.ACTION_DOWN:break; default:break; } return true;//suppress the ListView Slide. } returnSuper.ontouchevent (ev); }/** * Ready to drag, Initialize the image of the dragged item * * @param BM * @param y */private void startDrag (Bitmap bm, int Y) { /*** * Initialize WINDOW. */windowparams = new Windowmanager.layoutparams (); Windowparams.gravity = gravity.top; Windowparams.x = 0; Windowparams.y = Y-dragpoint + dragyoffset; Windowparams.width = WindowManager.LayoutParams.WRAP_CONTENT; Windowparams.height = WindowManager.LayoutParams.WRAP_CONTENT; Windowparams.flags = Windowmanager.layoutparams.flag_not_focusable//does not need to get focus | Windowmanager.layoutparams.flag_not_touchable//does not need to accept touch Events | Windowmanager.layoutparams.flag_keep_screen_on//keep the device normally open and keep the brightness constant. WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; The window fills the entire screen, ignoring the surrounding decorative borders (such as the status bar). This window takes into account the contents of the decorative Border. ImageView ImageView = new ImageView (getcontext ()); Imageview.setimagebitmap (bm); WindowManager = (windowmanager) GetContext (). Getsystemservice (context.window_service); Windowmanager.addview (imageView, windowparams); Dragimageview = imageView; /** * Drag execution, Execute in Move method * * @param y */public void Ondrag (int y) {int drag_top = Y-dragpo Int;//drag View top value cannot be 0, otherwise it is out of BOUNDS. If (dragimageview! = null && drag_top >= 0) {windowparams.alpha = 0.65f; Windowparams.y = Y-dragpoint + dragyoffset; Windowmanager.updateviewlayout (dragimageview, windowparams);//always Move (drag The moving core)}//to avoid sliding to the split line, the return-1 problem int tempposition = pointtoposition (0, y); If (tempposition! = Invalid_position) {dragendposition = tempposition; } onChange (y);//always Exchange Doscroller (y);//listview Move. }/*** * The movement of the LISTVIEW. * To understand the principle of movement: when I move to the lower end, the ListView swipe up, and when I move to the upper end, the ListView will Slide. * Just as opposed to the Actual. */public void Doscroller (int y) {//listview needs to fall if (y < UPSCROllbounce) {current_step = step + (upscrollbounce-y)/10;//step}//the ListView needs to slide on else if (y > Downscrollbounce) {current_step =-(step + (y-downscrollbounce))/10;//always pace} else { Current_step = 0; }//get your drag-and-drop slide to position and display item on the corresponding view (note: visible Section) (position) View view = Getchildat (dragendposition-getfirstvisiblepo Sition ()); True scrolling method Setselectionfromtop () If (view! = Null) setselectionfromtop (dragendposition, view.gettop () + C urrent_step); }/** * Stop dragging, delete image */public void Stopdrag () {if (dragimageview! = Null) {WINDOWMANAGER.R Emoveview (dragimageview); Dragimageview = null; }}/*** * Drag always change */private void OnChange (int y) {//data Exchange if (dragendposition < GE Tadapter (). getcount ()) {draglistadapter adapter = (draglistadapter) Getadapter (); If (dragendposition! = Temchangid){adapter.update (temchangid, dragendposition); Temchangid = Dragendposition;//will Click on the original location position to pay temporary, to determine whether Transposition. }}//in order to avoid sliding to the split line, return 1 question int tempposition = pointtoposition (0, y); If (tempposition! = Invalid_position) {dragendposition = tempposition; }//out-of-bounds processing (if It is above the second top, place it in the first Position) if (y < Getchildat (0). GetTop ()) {//out of the upper boundary Dragendposition = 0; If you drag over the bottom of the last item then prevent the bottom-most} else if (y > Getchildat (getchildcount ()-1). getbottom ()) {//out of the lower boundary Dragendposition = Getadapter (). getcount ()-1; }}/** * Drag down when * * @param y */public void onDrop (int y) {//data Exchange if (DRAGENDPO Sition < Getadapter (). GetCount ()) {draglistadapter adapter = (draglistadapter) Getadapter (); Adapter.notifydatasetchanged ();//refresh. LOG.D ("wbl", "dragendposition: "+ dragendposition); LOG.D ("wbl", "dragbeginposition:" + dragbeginposition); After the transposition succeeds the callback if (mmydraglistener! = Null) {mmydraglistener.ondragfinish (dragbeginposition, dragen dposition); }}}//the callback interface after the successful transposition interface Mydraglistener {void ondragfinish (int srcpositon, int finalposition); }//set the callback interface after a successful transposition public void Setmydraglistener (mydraglistener listener) {mmydraglistener = listener; }}</pre><p><p></p></p><p><p><br></p></p><span style="font-size:18px"><span style="font-size:18px">draglistadapter:</span></span><p><p></p></p><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_2_7362415" name="code" class="java">Package Com.lunge.dragablelistview;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import android.widget.TextView; Import java.util.arraylist;/** * Created by Lunger on 8/17 11:21 */class Draglistadapter extends Baseadapter {pri Vate arraylist<string> mdatas; Private context context; Public draglistadapter (context context, arraylist<string> arraytitles) {this.context = context; This.mdatas = arraytitles; } @Override public view getView (final int position, view convertview, viewgroup parent) {view view; /*** * Try to instantiate the new one every time here, so that there is no confusion when dragging the LISTVIEW. * Specific reasons are unknown, but this has been tested, there is no Confusion. Although the efficiency is not high, but do drag Lisview enough. */view = Layoutinflater.from (context). Inflate (r.layout.drag_list_item, null); TextView TextView = (TextView) view. Findviewbyid (r.id.tv_name); TeXtview.settext (mdatas.get (position)); Return view; }/*** * Dynamically modifies the orientation of the LISTVIIW. (data shift) * * @param start click Move position * @param end release Time position */p ublic void update (int start, int end) {String data = Mdatas.get (start); Mdatas.remove (start);//delete the item mdatas.add (end, data);//add Delete Item notifydatasetchanged ();//refresh listview} @Ov erride public int GetCount () {return mdatas.size (); } @Override public Object getItem (int position) {return mdatas.get (position); } @Override public long getitemid (int Position) {return position; }}</pre><br><br><span style="font-size:18px"><span style="font-size:18px">Item Layout:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_3_9489769" name="code" class="java"><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_3_9489769" name="code" class="java"><?xml version= "1.0" encoding= "utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent "> <textview android:id= "@+id/tv_name" android:layout_width= "300px" android:layout_height= "100px" android: layout_centervertical= "true" android:gravity= "center" android:text= "Your infomation" android: textsize= "25px"/> <imageview android:id= "@+id/iv_move" android:layout_width= "53px" android:layout_height= "75px" android:layout_alignparentright= "true" android:layout_centervertical= " True " android:layout_marginright=" 20px " android:src=" @mipmap/ic_launcher "/></relativelayout ></pre></pre><p><p></p></p><p><p><br></p></p><span style="font-size:18px"><span style="font-size:18px">mainactivity:</span></span><p><p></p></p><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_4_7090198" name="code" class="java">Package Com.lunge.dragablelistview;import Android.os.bundle;import android.support.v7.app.AppCompatActivity; Import Android.widget.toast;import java.util.arraylist;/** * Created by Lunger on 8/17 11:21*/public class Mainactivi Ty extends appcompatactivity {private draglistview mLv; Private Arraylist<string> mdatas; @Override protected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); MLv = (draglistview) Findviewbyid (r.id.lv); Mdatas = new Arraylist<> (); for (int i = 0; i < i++) {mdatas.add ("Monster kill" + i); } mlv.setadapter (new Draglistadapter (this, mdatas)); Mlv.setmydraglistener (new draglistview.mydraglistener () {@Override public void ondragfinish (int SRC positon, int Finalposition) {toast.maketext (mainactivity.this, "beginpoisiton:" + Srcpositon + "... Endpo Sition: "+finalposition, toast.length_long). Show (); } }); }}</pre><p><p></p></p><p><p><br></p></p><span style="font-size:18px"><span style="font-size:18px">Main Layout:</span></span><p><p></p></p><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_5_4408003" name="code" class="java"><pre code_snippet_id="1840703" snippet_file_name="blog_20160819_5_4408003" name="code" class="java"><?xml version= "1.0" encoding= "utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk /res/android " xmlns:tools=" http://schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height= "match_parent" android:paddingbottom= "@dimen/activity_vertical_margin" android: paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools:context= " Com.lunge.dragablelistview.MainActivity "> <com.lunge.dragablelistview.draglistview android:id= "@+id/lv" android:layout_width= "wrap_content" android:layout_height= "match_parent" /></ Relativelayout></pre></pre><br><br><p><p></p></p><p><p><br></p></p><p><p>Android can drag and drop item Listview--draglistvie</p></p></span>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service