Android Custom View View

Source: Internet
Author: User

Creating a new view will meet our unique UI needs.

This article describes the interface UI of the compass that will be used in compass development, and provides a deep understanding of custom views by inheriting custom views implemented by the view class.

Realize:


Source:

Layout file Activity_main (where Compassview inherits the view Class):

<framelayout 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 ">    <com.professionalandroiddemo6.compassview        android:id=" @+id/compassview "        Android:layout_width= "Match_parent"        android:layout_height= "Match_parent"/></framelayout>

Under the Res/values folder:

String.xml:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <string    name= "App_name" > professionalandroiddemo6</string>    <string name= "action_settings" font = "14SP" >settings</string >    <string name= "Hello_world" >hello world!</string><string name= "North" >N</string> <string name= "East" >e</string><string name= "South" >s</string><string name= "West" >W </string></resources>

Colors.xml:

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <color name= "Background" > #F555 </color >    <color name= "Maker" > #AFFF </color>    <color name= "text" > #AFFF </color>    < /resources>
code files;

Mainactivity:

Package Com.professionalandroiddemo6;import Android.app.activity;import Android.os.bundle;public class MainActivity Extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);}}

Compassview:

Package com.professionalandroiddemo6;/** * Custom View--Compass interface */import Android.content.context;import Android.content.res.resources;import Android.graphics.canvas;import Android.graphics.paint;import Android.util.attributeset;import Android.view.view;import Android.view.accessibility.accessibilityevent;public Class Compassview extends View {private Paint markerpaint;private paint circlepaint;private paint textpaint;private strin G North, South, east, West;private int textheight;private String dirstring;private float bearing;public void Setbearing (fl Oat _bearing) {bearing = _bearing;sendaccessibilityevent (accessibilityevent.type_view_text_changed);} public float getbearing () {return bearing;} Public Compassview (Context context) {super (context); Initcompassview ();} Public Compassview (context context, AttributeSet Attrs) {Super (context, attrs); Initcompassview ();} Public Compassview (context context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr); Initcompassview ();} Private VOID Initcompassview () {setfocusable (true); Resources resources = This.getresources (); circlepaint = new Paint (paint.anti_alias_flag); Circlepaint.setcolor ( Resources.getcolor (R.color.background)); Circlepaint.setstrokewidth (1); Circlepaint.setstyle (Paint.Style.FILL_ And_stroke), north = resources.getstring (R.string.north), south = resources.getstring (R.string.south), east = Resources.getstring (r.string.east); west = resources.getstring (r.string.west); textpaint = new Paint (paint.anti_alias _flag); Textpaint.setcolor (Resources.getcolor (R.color.text)); Textpaint.settextsize ((float) 30);//This sets the size of the font that will be displayed. TextHeight = (int) textpaint.measuretext ("YY"), Markerpaint = new Paint (paint.anti_alias_flag); Markerpaint.setcolor ( Resources.getcolor (R.color.maker));} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//Compass is a circle that fills as much space as possible by setting the shortest bounds, Height or width to set the measurement size. int measuredwidth = measure (widthmeasurespec); int measuredheight = measure (HEIGHTMEASURESPEC); int d = Math.min ( Measuredwidth, MEAsUredheight); Setmeasureddimension (d, D);} private int measure (int measurespec) {int result = 0;//decodes the measurement description int specmode = Measurespec.getmode (measurespec); int SpecS ize = Measurespec.getsize (Measurespec); if (Specmode = = measurespec.unspecified) {//If no bounds are specified, the default return value is 200result = 200;} else {//because you want to populate the available space, always return the entire available boundary result = specsize;} return result;} @Overrideprotected void OnDraw (canvas canvas) {//locates the center of the control and stores the length of the minimum edge as the radius of the compass. int mmeasuredwidth = Getmeasuredwidth (), int mmeasuredheight = Getmeasuredheight (); int px = Mmeasuredwidth/2;int py = mMe Asuredheight/2;int radius = math.min (px, py);//Use the Drawcircle method to draw the boundary of the compass character and color it for Beijing. Canvas.drawcircle (px, py, radius, circlepaint), Canvas.save (), Canvas.rotate (-bearing, px, py);//The only thing left to do is draw the mark. Rotate the canvas one circle and draw a marker every 15 degrees, drawing an abbreviation for One Direction every 45 degrees. int textWidth = (int) textpaint.measuretext ("W"), int cardinalx = Px-textwidth/2;int Cardinaly = Py-radius + Textheig ht;//draws a marker every 15 degrees and draws one text for each 45 degrees for (int i = 0; i < i++) {canvas.drawline (px, Py-radius, PX, py-rAdius +, Markerpaint); Canvas.save () canvas.translate (0, textHeight);//Draw Basic azimuth if (i 6 = = 0) {switch (i) {case 0: {DirS Tring = North;int Arrowy = 2 * textheight;canvas.drawline (px, Arrowy, px-5, 5 * textheight,markerpaint); Canvas.drawline ( PX, arrowy, px + 5, 5 * textheight,markerpaint);} Break;case 6:dirstring = east;break;case 12:dirstring = south;break;case 18:dirstring = west;break;} Canvas.drawtext (dirstring, Cardinalx, Cardinaly, textpaint);} else if (i 3 = = 0) {//Draw text every 45 degrees String angle = string.valueof (i *); float angletextwidth = textpaint.measuretext (angle) ; int angletextx = (int) (PX-ANGLETEXTWIDTH/2); int angletexty = Py-radius + textheight;canvas.drawtext (angle, Anglete XtX, Angletexty, textpaint);} Canvas.restore (); Canvas.rotate (px, py);} Canvas.restore ();} @Overridepublic boolean dispatchpopulateaccessibilityevent (Accessibilityevent event) { Super.dispatchpopulateaccessibilityevent (event), if (Isshown ()) {String bearingstr = string.valueof (bearing); Bearingstr.lEngth () > accessibilityevent.max_text_length) bearingstr = bearingstr.substring (0,accessibilityevent.max_text_ LENGTH); Event.gettext (). Add (bearingstr); return true;} return false;}}

Source code Download:

Click to download the source code

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.