The essential
1 PackageCom.example.administrator.mystudent.ButtonMove;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 ImportAndroid.util.DisplayMetrics;6 ImportAndroid.util.Log;7 Importandroid.view.MotionEvent;8 ImportAndroid.view.View;9 ImportAndroid.widget.Button;Ten ImportAndroid.widget.Toast; One A ImportCOM.EXAMPLE.ADMINISTRATOR.MYSTUDENT.R; - - Public classButtonmoveactivityextendsActivity { the - PrivateButton btn1; - Private intScreenWidth; - Private intScreenHeight; + - @Override + protected voidonCreate (Bundle savedinstancestate) { A Super. OnCreate (savedinstancestate); at Setcontentview (r.layout.activity_button_move); - - //displaymetrics take screen size resolution -Displaymetrics dm=getresources (). Getdisplaymetrics (); -Screenwidth=Dm.widthpixels; -Screenheight=dm.heightpixels-50; in -BTN1 =(Button) Findviewbyid (R.ID.BTN1); toBtn1.setontouchlistener (NewMyontouchlistener ()); + - } the * classMyontouchlistenerImplementsView.ontouchlistener { $ intlastx,lasty;Panax Notoginseng - @Override the Public BooleanOnTouch (View V, motionevent event) { + intEa=event.getaction (); ALOG.I ("TAG", "Touch:" +ea); the + Switch(EA) { - CaseMotionevent.action_down: $ $Lastx= (int) event.getrawx ();//gets the original x-coordinate of the touch event touch Location -Lasty= (int) Event.getrawy (); - Break; the - CaseMotionevent.action_move:Wuyi intDx= (int) event.getrawx ()-Lastx; the intDy= (int) Event.getrawy ()-lasty; - Wu intL=v.getleft () +DX; - intB=v.getbottom () +dy; About intR=v.getright () +DX; $ intT=v.gettop () +dy; - - //The following determines whether the move exceeds the screen - if(l<0){ AL=0; +r=l+v.getwidth (); the } - $ if(t<0){ theT=0; theb=t+v.getheight (); the } the - if(r>screenwidth) { inR=ScreenWidth; thel=r-v.getwidth (); the } About the if(b>screenheight) { theb=ScreenHeight; thet=b-v.getheight (); + } - v.layout (L, T, R, b); the BayiLastx= (int) event.getrawx (); theLasty= (int) Event.getrawy (); the Toast.maketext (Getapplicationcontext (), -"Current Location:" +l+ "," +t+ "," +r+ "," +B, - toast.length_short). Show (); the the //using the Invalidate () Refresh interface (post multithreading) the v.postinvalidate (); the Break; - Casemotionevent.action_up: the Break; the } the return false;94 } the } the the}
Android Removable button