Control drag Displacement position

Source: Internet
Author: User

简单的一个控件拖拽交换位置Demo,有些场景下会用到,关于此类功能网上有很多例子,而且Google官方API中也有相应的接口,对这种业务需求进行了一定逻辑封装。这里没有采用官方接口,单纯的从触摸事件入手来简单的实现控件位置交换。写代码之前先理清楚实现的思路,这里从控件的触摸事件入手,触摸事件有ACTION_DOWN、ACTION_MOVE、ACTION_UP这几个状态,下面先把实现逻辑的思路写出来:1.界面加载完成后用一个List记录各个子控件相对于父控件的坐标,同时将这些子控件放入一个List中备用。2.分别给每个子控件添加触摸事件,拖拽交换的主要逻辑在触摸事件中完成。3.触摸事件:    当手指落下时:记录当前手指坐标startX、startY,记录当前触摸的控件a的初始位置;    当手指开始移动:移动过程中onTouch方法会不断执行,这里要做的就是不断的用View的layout(l,t,r,b)方法不断的将被触摸的控件定位到手指移动过的地方,产生的效果就是被触摸的控件a跟随手指进行滑动。获取手指的实时位置与ACTION_DOWN时的位置相减得出手指移动的差值,获取控件a四条边相对于父控件的坐标位置,将这四个坐标分别加上这个差值得出新的四边坐标,调用View的layout(l,t,r,b)方法重新定位控件a,然后重新给startX、startY赋值。    当手指抬起:判断当前手指位置是否在某一个子控件b的四条边坐标内部,如果不在则让控件a定位回初始位置,如果在则让控件a和控件b交换位置。有了以上的逻辑分析是不是思路清晰了许多呢,下面就一步步来实现上面的逻辑首先定义一个布局文件,其中包含几个Button:
<linearlayout 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"tools:context=". Mainactivity "Android:id="@+id/ll_main"android:orientation="Vertical"android:paddingtop="@dimen/dimen_80px"> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:text="Button1"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"/> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"android:text="Button2"/> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"android:text="Button3"/> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"android:text="Button4"/> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"android:text="Button5"/> <button android:layout_width="Match_parent"android:layout_height="Wrap_content"android:paddingtop="@dimen/dimen_40px"Android:paddingbottom="@dimen/dimen_40px"android:text="Button6"/></linearlayout>

Here is the Mainactivity class

 PackageCom.donz.exchangebutton;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.MotionEvent;ImportAndroid.view.View;ImportAndroid.widget.LinearLayout;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map; Public  class mainactivity extends actionbaractivity {     Public Static FinalString TAG ="Mainactivity";PrivateLinearLayout Ll_main;PrivateList<map<string,integer>> buttons_locations;Private intParentt;Private intParentl;PrivateView[] views;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Buttons_locations =NewArraylist<> ();        Initviews ();    Inittouchevent (); }Private void inittouchevent() { for(intj =0; J<ll_main.getchildcount (); j + +) {//Give each button a fixed-point click eventLl_main.getchildat (j). Setontouchlistener (NewView.ontouchlistener () {intStartX;intStarty;intXintY@Override                 Public Boolean OnTouch(View V, motionevent event) {V.bringtofront ();Switch(Event.getaction ()) { CaseMotionevent.action_down://The starting position of the finger fallStartX = (int) event.getrawx (); Starty = (int) Event.getrawy ();int[] location =New int[2];                            V.getlocationonscreen (location); x = location[0]; y = location[1]; Break; CaseMotionevent.action_move:intNewx = (int) event.getrawx ();intNewy = (int) Event.getrawy ();//Calculates the offset of the finger at x and y                            intDex = Newx-startx;intDey = Newy-starty;//Calculates the top and bottom positions of the button in real time, relative to the parent element                            intL = V.getleft ();intt = V.gettop ();intR = V.getright ();intb = V.getbottom ();//button should be in the new position after the finger is moved                            intNEWL = L + dex;intNEWR = R + dex;intNewt = t + dey;intNewb = b + dey;//Put button layout to new locationV.layout (NEWL, Newt, NEWR, newb);//Reset the starting position of the fingerStartX = (int) event.getrawx (); Starty = (int) Event.getrawy (); Break; CaseMOTIONEVENT.ACTION_UP:intNewfingerx = (int) event.getrawx ();intNewfingery = (int) Event.getrawy ();//traverse the entire position list to compare whether the current finger position is coincident with another button position, and if so, place the button back in the original position                             for(inti =0; I < buttons_locations.size (); i++) {if(I==v.gettag ()) {Continue; } map<string, integer> m = Buttons_locations.get (i);intBTNL = M.get ("L");intBTNT = M.get ("T");intBtnr = M.get ("R");intBTNB = M.get ("B");if(Newfingerx > Btnl && newfingery > Btnt && newfingerx < Btnr && Newfingery < BTNB) {//within a button rangeV.layout (Btnl-parentl, Btnt-parentt, Btnr-parentl, Btnb-parentt); Views[i].layout (X-parentl, Y-parentt, X + v.getwidth ()-Parentl, y + v.getheight ()-Parentt);//Replace the value of viewviews[(int) (V.gettag ())] = Views[i]; views[(int) (V.gettag ())].settag (V.gettag ());                                    Views[i] = v; Views[i].settag (i);//Replace the value of mapButtons_locations.set (I,buttons_locations.get (int) (V.gettag ()))); Buttons_locations.set ((int) (V.gettag ()), m);return true; }                            }//Return to the original locationV.layout (X-parentl, Y-parentt, x +v.getwidth ()-Parentl, Y+v.getheight ()-Parentt); Break; }return true;        }            }); }    }@Override     Public void onwindowfocuschanged(BooleanHasfocus) {Super. onwindowfocuschanged (Hasfocus);if(Hasfocus) {int[] Parentlocation =New int[2];            Ll_main.getlocationonscreen (parentlocation); Parentl = parentlocation[0]; Parentt = parentlocation[1];intCount = Ll_main.getchildcount (); views =NewView[count]; for(inti =0; i<count;i++) {map<string,integer> Map =NewHashmap<> ();int[] location =New int[2];                Ll_main.getchildat (i). Getlocationonscreen (location);                Ll_main.getchildat (i). Settag (i); Map.put ("L", location[0]); Map.put ("T", location[1]); Map.put ("R", Ll_main.getchildat (i). GetWidth () +location[0]); Map.put ("B", Ll_main.getchildat (i). GetHeight () +location[1]);                Buttons_locations.add (map);            Views[i] = Ll_main.getchildat (i); }        }    }Private void initviews() {Ll_main = (linearlayout) Findviewbyid (R.id.ll_main); }}

The key logic in the code are given detailed comments, believe not ugly understand, need to pay attention to the points:

The 1.getRawX (), Getrawy () method is to get the coordinates of the finger on the phone screen, while Getx (), GetY () are the coordinates of the acquisition point relative to the parent control. GetLeft (), GetRight (), GetTop (), Getbottom () are the coordinate positions of the control's four edges relative to the control's parent control, and the width height between them and the control is allowed to be converted.
2. Some property values of the controls in the layout file must be obtained after the interface has been loaded, if obtained directly in the activity's OnCreate () method. This is because layout rendering takes time, and details can be seen in the Onmeasure () and OnLayout () methods of the view.

Here is just to provide a thought and approximate implementation, all aspects are relatively rough, because the displacement is the space itself rather than the text content, the size of the individual controls are not processed, if the size of the words will be problematic. Some animation effects can be added to the experience.

If the content of this article is helpful to you, please move your hand to the top of the button at the end of the article below, and appreciate it!

Source Link (Android Studio can be imported directly, eclipse too troublesome words directly to build a new project code sticky past can be):

Source point I, I

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Control drag Displacement position

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.