Android Learning Series (10)-drag and drop the App list listview (top)

Source: Internet
Author: User
Tags addall

I have studied the implementation of drag-and-drop listview for a long time and have benefited a lot.
In view of the fact that the content on the Internet is small and simple, and the specific implementation process may be helpful to everyone, in order to be detailed without distortion, we will analyze it step by step and divide it into two articlesArticle.

I. preparation.

1. Requirements
Preliminary: Implement the drag-and-drop effect of the list (see touchinterceptor. Java source code in packages/apps/music under the android source code ).
(This Article is not fully implemented in music,CodeThe implementation method has been adjusted to remove a lot of irrelevant things for your convenience, and the effect has been changed to another one.

I personally think it is a simpler and more efficient set .)
Expansion: Learn from the previous articleAndroid Learning Series (9) -- group listview of App listTo achieve the drag and drop effect of the group list.
The following is an example of initial implementation.

2. Build the main interface draglistactivity. Java and the main layout drag_list_activity.xml.

 
Public class draglistactivity extends activity {// data list private list <string> List = NULL; // data adapter private draglistadapter adapter = NULL; // Save the group tag public static list <string> groupkey = new arraylist <string> (); // group a private list <string> navlist = new arraylist <string> (); // group two private list <string> morelist = new arraylist <string> (); @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. drag_list_activity); // initialize the sample data initdata (); // The following describes draglistview = (draglistview) findviewbyid (R. id. drag_list); adapter = new draglistadapter (this, list); draglistview. setadapter (adapter );}}

3. The layout of list items is drag_list_item.xml.

 
<? XML version = "1.0" encoding = "UTF-8"?> <! -- To emphasize one point, use relative layout --> <relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: id = "@ + ID/drag_list_item_text" Android: layout_width = "wrap_content" Android: layout_height = "@ dimen/drag_item_normal_height" Android: paddingleft = "5dip" Android: layout_alignparentleft = "true" Android: layout_centervertical = "true" Android: gravity = "center_vertical"/> <imageview Android: Id = "@ + ID/drag_list_item_image" Android: src = "@ drawable/list_icon" Android: layout_alignparentright = "true" Android: layout_centervertical = "true" Android: layout_width = "wrap_content" Android: layout_height = "@ dimen/drag_item_normal_height"/> </relativelayout>

4. Prepare sample data.
I have prepared two groups of data and initialized them in the initdata () method mentioned above.

 
Public void initdata () {// data result list = new arraylist <string> (); // groupkey stores the group tag groupkey. add ("group A"); groupkey. add ("group B"); For (INT I = 0; I <5; I ++) {navlist. add ("A option" + I);} List. add ("group A"); list. addall (navlist); For (INT I = 0; I <8; I ++) {morelist. add ("B Option" + I);} List. add ("group B"); list. addall (morelist );}


The groupkey of the group tag set is defined here and will be used for grouping.

5. Customize the draglistadapter class.
Then we set up a data adapter to fill the list data into the listview.

Public static class draglistadapter extends arrayadapter <string> {public draglistadapter (context, list <string> objects) {super (context, 0, objects );} @ override public view getview (INT position, view convertview, viewgroup parent) {view = convertview; If (view = NULL) {// load list item template view = layoutinflater. from (getcontext ()). inflate (R. layout. drag_list_item, null);} textview = (textview) view. findviewbyid (R. id. drag_list_item_text); textview. settext (getitem (position); Return view ;}}

Note that getitem (position) will obtain the position T (here it is a string) in the array adapter, a better method.

At this point, we have prepared a normal data list with the following results:
 

II. Implementation

The above part is a preparation. Next we will use the custom listview to override the onintercepttouchevent () and ontouchevent () methods in the listview to respond to the touch event and make corresponding interface adjustments (selected, drag, refresh the interface after the data is changed.

6. Custom View class.

 
// Customize the listview and prepare to convert it to the desired listview. // The advantage is that we can not only directly use the listview many stable off-the-shelf methods, in addition, you can override the behavior of listview (using the inheritance feature of Java object-oriented, I like to analyze the characteristics, principles, and modes of object-oriented in any code) public class draglistview extends listview {private int scaledtouchslop; // determines the sliding distance. Public draglistview (context, attributeset attrs) {super (context, attrs) will be used in scroll ); scaledtouchslop = viewconfiguration. get (context ). getscaledtouchslop ();}}

7. Override the onintercepttouchevent () method of the touch interception event ().
in order to listen to the touch event in listview when the child control responds to the touch event, we rewrite this method and perform initialization. Here we capture the down event. In the down event, we make some preparations for dragging:
1) Get the click data item and initialize some variables;
2) determine whether to drag the image or just click it.
3) If you drag the image, create a drag image.
these operations are very important for the execution of the drag operation.

// The following defines all the variables to be used: Private imageview dragimageview; // the image of the dragged item is actually an imageview private int dragsrcposition; // The original position of the finger-dragging item in the list is private int dragposition; // the position of the current drag item in the list is private int dragpoint; // The position in the current data item is private int dragoffset; // The distance between the current view and the screen (here only the y direction is used) Private windowmanager; // windows window control class private windowmanager. layoutparams windowparams; // The Private int scaledtouchslop parameter used to control the display of Drag and Drop items; // you can determine Distance from private int upscrollbounce; // when dragging, the boundary that begins to scroll up is private int downscrollbounce; // when dragging, the boundary that begins to scroll down @ override public Boolean onintercepttouchevent (motionevent eV) {// capture the down event if (ev. getaction () = motionevent. action_down) {int x = (INT) eV. getx (); int y = (INT) eV. gety (); // The Position of the selected data item. Use the pointtoposition (x, y) method that comes with listview to dragsrcposition = dragposition = pointtoposition (x, y ); // if it is an invalid position (beyond the boundary, split line, etc.), if (DRA Gposition = adapterview. invalid_position) {return Super. onintercepttouchevent (EV);} // obtain the view of the selected item // getchildat (INT position) display the view of the position of display on the Interface // getfirstvisibleposition () returns the position of the first display view on the page in the adapter, which may be 0 or 4 viewgroup itemview = (viewgroup) getchildat (dragposition-getfirstvisibleposition ()); // dragpoint: Click the relative position in the view. // The offset between the dragoffset screen position and the current listview position. Here, only the values on the Y coordinate are used. // Dragpoint = Y-itemview. gettop (); dragoffset = (INT) (ev. getrawy ()-y); // get the drag icon on the right. This is a good way to drag and drop the group behind it. View dragger = itemview. findviewbyid (R. id. drag_list_item_image); // if it is on the right side (drag the right side of 20px on the left side of the image) if (dragger! = NULL & x> dragger. getleft ()-20) {// ready to drag // scroll variable during initialization drag // scaledtouchslop defines the deviation position of the drag (generally +-10) // when upscrollbounce is in the upper part of the screen (the upper part of the screen) or in the upper part of the screen, the drag boce is executed. The downscrollbounce defines upscrollbounce = math. min (Y-scaledtouchslop, getheight ()/3); downscrollbounce = math. max (Y + scaledtouchslop, getheight () * 2/3); // set drawingcache to true to get the selected image BM, which is the portrait itemview we drag. setdrawingcacheenabled (true); bitmap Bm = bitmap. createbitmap (itemview. getdrawingcache (); // ready to drag the image (add the image to the current window without dragging it. The drag operation is executed in the ontouchevent () Move) startdrag (BM, y);} return false;} return Super. onintercepttouchevent (EV );}

you may be dazzled when you see a lot of variables and operations above. You can go back and understand them later.
start to drag the image startdrag () method:

/*** Ready to drag, initialize the image of the drag item * @ Param BM * @ Param y */Public void startdrag (Bitmap BM, int y) {// release the image, when preparing the image, prevent the image from being released. Execute stopdrag (); windowparams = new windowmanager every time. layoutparams (); // calculate the relative position in the Y direction from top to bottom, windowparams. gravity = gravity. top; windowparams. X = 0; windowparams. y = Y-dragpoint + dragoffset; windowparams. width = windowmanager. layoutparams. wrap_content; windowparams. height = windowmanager. layoutparams. wrap_content; // The following parameters help to accurately locate the selected item click position. Then, you can copy windowparams. flags = windowmanager. layoutparams. flag_not_focusable | windowmanager. layoutparams. flag_not_touchable | windowmanager. layoutparams. flag_keep_screen_on | windowmanager. layoutparams. flag_layout_in_screen; windowparams. format = pixelformat. translucent; windowparams. windowanimations = 0; // Add the image imagview to the current view. imageview = new imageview (getcontext (); imageview. setimagebitmap (BM); windowmanager = (windowmanager) getcontext (). getsystemservice ("window"); windowmanager. addview (imageview, windowparams); // reference the image imageview to the variable drawimageview for subsequent operations (drag, release, etc.) dragimageview = imageview ;}

Stopdrag () method:

 
/*** Stop dragging and remove the avatar of the drag item */Public void stopdrag () {If (dragimageview! = NULL) {windowmanager. removeview (dragimageview); dragimageview = NULL ;}}

Run and see. We didn't respond when we click an item. But if we observe it carefully, there is actually a faint shadow on the click item. This is the image of the click item we define, the next step is to drag the image, put down the image, insert the data item at the put-down position, and delete the original data item location. This part of content and subsequent extended content will be further analyzed and implemented in the next article.
To be continued...

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.