Android 360 degree Joystick

Source: Internet
Author: User
Tags gety pow set background
<span id="Label3"></p><p><p>Create a new class. For example, Mysurfaceview</p></p><pre class="brush:java;toolbar:false">package com.example.blt;import android.annotation.suppresslint;import android.content.context; import android.graphics.canvas;import android.graphics.color;import android.graphics.paint; import android.graphics.pixelformat;import android.graphics.porterduff.mode;import  Android.util.attributeset;import android.view.motionevent;import android.view.surfaceholder;import  android.view.SurfaceView;import android.view.SurfaceHolder.Callback;public class  Mysurfaceview extends surfaceview implements callback {private surfaceholder  sfh;private canvas canvas;private paint paint;private int coordinate;//   Fixed rocker background circle radius private int rockercircler, smallrockercircler;//  the x, y coordinates of the joystick and the radius of the joystick private  float smallrockercirclex, smallrockercircley;private rudderlistener listener =  null; //  Event Callback Interface Public mysuRfaceview (context context)  {super (Context);} Public mysurfaceview (context context, attributeset as)  {super (context, as); This.setkeepscreenon (true); sfh = getholder (); sfh.addcallback (this);p aint = new paint ( );p aint.setcolor (color.green);p aint.setantialias (true);//  anti-aliasing setfocusable (true); Setfocusableintouchmode ( true); setzorderontop (true); sfh.setformat (pixelformat.transparent);//  Set Background transparency}public void  surfacecreated (surfaceholder holder)  {//  Get control minimum value int little = this.getwidth ()  < this.getheight ()  ? this.getwidth ():  this.getheight ();//  Draw smallrockercirclex = smallrockercircley = coordinate = little /based on screen size  2;//  Fixed rocker background circle radius rockercircler =  (int)   (little * 0.35);//  Joystick radius smallrockercircler =  (int)   (little * 0.15);d Raw ();} /*** *  gets the radian between two points  */puBlic double getrad (float px1, float py1, float px2, float py2)  {//  get a distance of two points x float x = px2 - px1;//  get two points y distance float y =  py1 - py2;//  figure out the hypotenuse length float xie =  (float)  math.sqrt (math.pow (x, 2)  +  math.pow (y, 2));//  obtains the cosine of this angle (through the theorem &nbsp in trigonometric functions;: adjacent edge/hypotenuse = Angle Cosine) float cosangle = x  / xie;//  obtains the Radian float rad =  (float)  math.acos (cosangle);//  by the inverse cosine theorem to its angle. Note: when the position of the touchscreen is Y-coordinate < The y-coordinate of the joystick we want to take the inverse value -0~-180if  (py2 < py1)  {rad = -rad;} return rad;} @SuppressLint ("clickableviewaccessibility") @Overridepublic  boolean ontouchevent (motionevent  Event)  {if  (event.getaction ()  == motionevent.action_down| |  event.getaction ()  == motionevent.action_move)  {//  when the touchscreen area is not in the active range if  (math.sqrt ( Math.pow ((coordinate -  (int)  event.getX ()),  2) + math.pow ((coordinate -  (int)  event.gety ()),  2)  >=  Rockercircler)  {//  Get the angle Double temprad = getrad (coordinate, coordinate, which is formed by the rocker and touch point  event.getx (), event.gety ());//  guarantees the length limit of the inner small circle movement Getxy (coordinate, coordinate, rockercircler,  temprad);}  else {//  if the center point of the ball is smaller than the active area, the smallrockercirclex =  (int)  event.getx () can be moved as the user touches the Screen. smallrockercircley =  (int)  event.gety ();}}  else if  (event.getaction ()  == motionevent.action_up)  {//  The position of the joystick to restore the joystick when the key is released is the initial position smallrockercirclex = coordinate; smallrockercircley = coordinate;} Draw ();if  (listener != null)  {listener.onsteeringwheelchanged ((smallrockercirclex -  coordinate)/ rockercircler,  (coordinate - smallrockercircley)/ RockerCircleR);} return true;} /** *  *  @param  r *  &nbsRotation point of p;          circular motion  *  @param  centerX *              Rotary point x *  @param  centery *              Rotary point y *  @param  rad  *             rotation of radians  */public void  Getxy (float centerx, float centery, float r, double rad)  {//  Gets the x-coordinate of the circular motion smallrockercirclex =  (float)   (r * math.cos (RAD))  + centerx;//   Get the y-coordinate of the circular motion smallrockercircley =  (float)   (r * math.sin (RAD))  + centery;} Public void draw ()  {try {canvas = sfh.lockcanvas ();// canvas.drawColor ( Color.white) Canvas.drawcolor (color.transparent, mode.clear);//  Clear the screen//  set Transparency Paint.setcolor ( color.cyan);//  Draw joystick Background canVas.drawcircle (coordinate, coordinate, rockercircler, paint);p Aint.setcolor (Color.RED);//  Draw Joystick Canvas.drawcircle (smallrockercirclex, smallrockercircley,smallrockercircler, paint);}  catch  (exception e)  {// todo: handle exception} finally {try  {if  (canvas != null) sfh.unlockcanvasandpost (canvas);}  catch  (exception e2)  {}}}public void surfacechanged (surfaceholder holder,  int format, int width,int height)  {}public void surfacedestroyed ( Surfaceholder holder)  {}//  Set Callback interface Public void setrudderlistener (rudderlistener  Rockerlistener)  {listener = rockerlistener;}   Callback Interface public interface rudderlistener {void onsteeringwheelchanged (float cross,  float longitudinal);}}</pre><p><p><br></p></p><p><p>In the main form<br></p></p><pre class="brush:java;toolbar:false">package com.example.blt;import android.app.activity;import android.content.intent;import  Android.os.bundle;import android.util.log;import android.view.menu;import android.view.menuitem ; Import android.view.view;import android.view.view.onclicklistener;import android.widget.button ; import android.widget.textview;public class controlactivity extends activity {@ Overrideprotected void oncreate (bundle savedinstancestate)  {super.oncreate ( savedinstancestate); Setcontentview (r.layout.activity_control); mysurfaceview temp =  (mysurfaceview)  findviewbyid (r.id.rudder); temp.setRudderListener (new  mysurfaceview.rudderlistener ()  {@Overridepublic  void onsteeringwheelchanged (float  Cross, float longitudinal) &NBSP;{//&NBSP;TODO&NBSP;AUTO-GENERATED&NBSP;METHOD&NBSP;STUBLOG.V ("change ", " C " + cross + " L " + longitudinal);((TexTView)  findviewbyid (r.id.textview2)). setText ("c:"  + cross+  "l:"  + longitudinal);});( (Button)  findviewbyid (r.id.button2)). setonclicklistener (new onclicklistener ()  {@Overridepublic  void onclick (view v)  {// todo auto-generated method stub}}); @Overridepublic  boolean oncreateoptionsmenu (menu menu)  {// inflate the menu ;  this adds items to the action bar if it is present.//  getmenuinflater (). Inflate (r.menu.control, menu); return false;} @Overridepublic  boolean onoptionsitemselected (menuitem item)  {// handle action  bar item clicks here. The action bar will// automatically  handle clicks on the home/up button, so long// as you  Specify a parent activity in aNdroidmanifest.xml.int id = item.getitemid ();if  (id == r.id.action_settings)  {return true;} Return super.onoptionsitemselected (item);}}</pre><p><p>----------------------the main form XML </p> </p><pre class="brush:xml;toolbar:false"><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:background= "# FFFFFF "    android:paddingbottom=" @dimen/activity_vertical_margin "     android:paddingleft= "@dimen/activity_horizontal_margin"     android:paddingright= "@dimen/ Activity_horizontal_margin "    android:paddingtop=" @dimen/activity_vertical_margin "  >    <gridlayout        android:layout_width = "match_parent"         android:layout_height= "match_parent"          android:layout_alignparentleft= "true"          android:layout_alignparenttop= "true"         android:columncount= "3"  >         <com.example.blt.MySurfaceView             android:id= "@+id/rudder"              android:layout_width= "150dp"              android:layout_height= "150dp"              android:layout_column= "0"              android:layout_gravity= "left|bottom"  />        < Textview            android:id= "@+id/textView2"             android:layout_column= "1"              android:layout_gravity= "left|top"              android:text= "TextView"  />        < tablelayout            android:layout_column= "2"             android:layout_gravity= "bottom"              android:layout_row= "0"  >             <TableRow                 android:id= "@+id/tablerow1"                  android:layout_width= "WRAP_ Content "                 android:layout_height= "wrap_content" >                < textview                     android:id= "@+id/axis_x"                      android:layout_width= "wrap_content"                      android: layout_height= "wrap_content"                      android:text= "TextView"  />             </TableRow>             <TableRow                 andrOid:id= "@+id/tablerow2"                  android:layout_width= "wrap_content"                  android:layout_height= "wrap_content"  >                 <Button                     android:id= "@+ Id/button2 "                     android:layout_width= "wrap_content"                      android:layout_height= "wrap_content"                      android:text= "automatic"  />                < button                     android:id= "@+id/button3"                      android:layout_width= "wrap_content"                      android: layout_height= "wrap_content"                      android:text= "button"  />             </TableRow>             <TableRow                 android:id="@+id/tablerow3"                  android:layout_width= "wrap_content"                  android:layout_height= "wrap_content"  >                 <Button                     android:id= "@+id/ Button1 "                     android:layout_width= "wrap_content"                      android:layout_height= "wrap_content"                       android:text= "button"  /&Gt;                <button                      android:id= "@+id/button4"                      android:layout_width= "wrap_content"                      android:layout _height= "wrap_content"                      android:text= "button"  />             </TableRow>             <TableRow                 android:id= "@+Id/tablerow4 "                 Android:layout_width= "wrap_content"                  android:layout_height= "wrap_content"  >                 <Button                     android:id= "@+id/button5"                      android:layout_width= "wrap_content"                      android:layout_height= "wrap_content"                       android:text= "button"  />                <button                      android:id= "@+id/button6"                      android:layout_width= "wrap_content"                      android:layout _height= "wrap_content"                      android:text= "button"  />             </tablerow>        </ Tablelayout>    </gridlayout></relativelayout></pre><p><p>------------------------------apply to custom controls<br></p></p><p><p>This article is from the "stone kee stone" blog, Make sure to keep this source http://nutter.blog.51cto.com/7390238/1713478</p></p><p><p>Android 360 degree Joystick</p></p></span>

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.