Android custom View

Source: Internet
Author: User

Creating a new view will satisfy our unique UI needs.

This article introduces the Interface UI of the compass used in the development of the compass. by inheriting the custom View implemented by the View class, we can deeply understand the custom View.

Implementation:


Source code:

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" >    
 </frameLayout>

In the res/values Folder:

String. xml:

 
     
  
   ProfessionalAndroidDemo6
      
  
   Settings
      
  
   Hello world!
  
  
   N
  
  
   E
  
  
   S
  
  
   W
  
 

Colors. xml:

 
     
  
   #F555
      
  
   #AFFF
      
  
   #AFFF
      
 
Code file;

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 Pain T textPaint; private String north, south, east, west; private int textHeight; private String dirString; private float bearing; public void setBearing (float _ 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, TributeSet 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); circlePai Nt. 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); // set the font size to 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) {// The compass is a circle filled with as much space as possible, set the measurement size by setting the shortest boundary, height, or width. 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; // decode int specMode = MeasureSpec for the measurement description. getMode (measureSpec); int specSize = MeasureSpec. getSize (measureSpec); if (specMode = MeasureSpec. UNSPECIFIED) {// if no limit is specified, the default return value is 200 resul. T = 200;} else {// because you want to fill in the available space, the entire available boundary result = specSize is always returned;} return result ;} @ Overrideprotected void onDraw (Canvas canvas) {// locate the control center and store the minimum edge length as the radius of the compass. Int mMeasuredWidth = getMeasuredWidth (); int mMeasuredHeight = getMeasuredHeight (); int px = mMeasuredWidth/2; int py = mMeasuredHeight/2; int radius = Math. min (px, py); // use the drawCircle method to draw the boundary of the compass character and color it in Beijing. Canvas. drawCircle (px, py, radius, circlePaint); canvas. save (); canvas. rotate (-bearing, px, py); // The only thing you need to do is the painting mark. Rotate the canvas in a circle, draw a mark every 15 degrees, and draw a direction abbreviation every 45 degrees. Int textWidth = (int) textPaint. measureText ("W"); int cardinalX = px-textWidth/2; int cardinalY = py-radius + textHeight; // draw a tag every 15 degrees, draw a text for (int I = 0; I <24; I ++) {canvas. drawLine (px, py-radius, px, py-radius + 20, markerPaint); canvas. save (); canvas. translate (0, textHeight); // draw the basic orientation if (I % 6 = 0) {switch (I) {case 0: {dirString = 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 String angle = String every 45 degrees. valueOf (I * 15); float angleTextWidth = textPaint. measureText (angle); int angleTextX = (int) (px-angleTextWidth/2); int angleTextY = py-radius + textHeight; canvas. drawText (angle, angleTextX, angleTextY, textPaint);} canvas. restore (); canvas. rotate (15, px, py);} canvas. restore () ;}@ Overridepublic boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event) {super. dispatchPopulateAccessibilityEvent (event); if (isShown () {String bearingStr = String. valueOf (bearing); if (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 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.