Getting Started with Android custom controls (i)

Source: Internet
Author: User

As a creative developer, or the software has a higher requirement for UI design, you will often encounter situations where the control that comes with Android does not meet your needs, and we can only implement controls that are appropriate for the project. At the same time, Android allows you to inherit existing controls or implement your own controls to optimize the interface and create a richer user experience.

So how do you create a new control?


It depends on what the demand is.


1. You need to extend the basic functionality of the native control, and you only need to inherit and extend the control . By overriding its event, OnDraw, but always keeps the call of the parent method. such as inheriting from an existing high-level control, such as inheriting a TextView.


2. Sums of the functionality of several controls, this time to combine the controls to generate a new control by merging several controls. For example, in the ListView with an adapter to combine a variety of controls organically, and write a control is a combination of multiple controls, typically a custom layout, you can use a class to inherit a layout. This layout contains multiple controls.


3. Create a new control from scratch. Start drawing controls directly from view, ViewGroup


4. also do not forget, there is a good thing <include> tags. in a project we may need to use the same layout design, if it is written in an XML file, the code is very redundant, and very poor readability, so we can put the same layout of the code to write a separate module, and then use the time can be <include/ > tags to reuse layout code.

As Friends of Android app Development know, Android UI interface is composed of view and ViewGroup and its derived classes. Based on the principles of the Android UI design, we, as a developer, are fully able to develop customized components of the project as we wish. Where view is the base class for all UI components, ViewGroup is the container that holds the components, which itself is derived from view. The general structure of the Androidui interface can be found in the following:




It can be seen that the viewgroup as a container may contain a view as a leaf node, or it can be included as a lower-level sub-viewgroup, and the child ViewGroup can contain the view and viewgroup of the next layer of leaf nodes. In fact, this flexible view hierarchy can create a very complex UI layout, where developers can design and develop very sophisticated UI interfaces.


ViewGroup can be very powerful by rewriting onmeasure,onlayout to lay out and processing the view that joins it, and we'll start by learning the view class to derive the custom component:

The view component acts like a panel in swing in Java, is a rectangular white space without any content, and, for other UI controls on Android apps, inherits the view component and then draws it. So we derive our own controls by using the view subclass and overriding the view class's methods.

The Android Custom view implementation is simple:

inherit view, override constructors, OnDraw, (onmeasure) and other functions, listed below.


If a custom view needs to have a custom attribute, you need to create a attrs.xml under values. In which you define your properties. In an XML layout file that uses a custom view, you need to include xmlns: prefix = "http://schemas.android.com/apk/res/the package path where your custom view is located." When using custom attributes, use the prefix: property name, such as my : Textcolor= "...".

Let's look at the method of the view class first:

Category

Methods

Description

Creation

Constructors

There is a form of the constructor that was called when the view was created from code and a form that was called when the V Iew is inflated from a layout file. The second form should parse and apply any attributes defined in the layout file.

Onfinishinflate ()

Called after a view and all of its children have been inflated from XML.

Layout

onmeasure (int, int)

Called to determine the size requirements for this view and all of its children.

OnLayout (boolean, int, int, int, int)

Called when the This view should assign a size and position to all of its children.

onsizechanged (int, int, int, int)

Called when the size of this view has changed.

Drawing

OnDraw (Android.graphics.Canvas)

Called when the view should to render its content.

Event processing

OnKeyDown (int, keyevent)

Called when a new hardware key event occurs.

onKeyUp (int, keyevent)

Called when a hardware key up event occurs.

Ontrackballevent (motionevent)

Called when a trackball motion event occurs.

Ontouchevent (motionevent)

Called when a touch screen motion event occurs.

Focus

Onfocuschanged (boolean, int, android.graphics.Rect)

Called when the view gains or loses focus.

Onwindowfocuschanged (Boolean)

Called when the window containing the view gains or loses focus.

Attaching

Onattachedtowindow ()

Called when the view was attached to a window.

Ondetachedfromwindow ()

Called when the view was detached from its window.

onwindowvisibilitychanged (int)

Called when the visibility of the window containing the view had changed.

You may typically want to override the following methods:


1. Constructor, at least to get context


2.onFinishlnflate () This is a callback method when the app loads the component from an XML layout file and leverages

After it has been built, the method will be called back.


3.onMeasure (int,int): Call this method to detect the size of the view component and all the subcomponents it contains.


4.onlayout (boolean,int,int,int,int): When the component needs to allocate the position and size of its subcomponents,

The method will be called back. A method that is called when a layout in a view class is changed, which is a method that all view, ViewGroup, and its derived classes have, overloading the class to make custom processing when the layout changes, which is useful for implementing some effects.

5.onSizeChanged (int,int, int, int): Callback The method when the size of the component is changed.


6.onDraw (canves): Callback The method when the component is about to draw its contents. The method used for redrawing in the view class, which is the method that all view, ViewGroup, and its derived classes have, and is the most important method for the Android UI drawing. Developers can reload the method and draw their own various graphics and image effects within the overloaded method based on the parameter canvas.

7.onKeyDown (int,keyevent): Triggers the method when a key is pressed.


8.onKayUp (int,keyevent), which triggers the method when a key is released.


9.onTrackballEvent (Motionevent): This method is triggered when a trackball event occurs.


10.onTouchEvent (Motionevent): This method is triggered when a touch screen event occurs.


11.onWindowFocuschanged (Boolean): This method is triggered when the component gets or loses focus.


12.onAttachedToWindow (): This method is triggered when the component is put into a window.


13.onDetachedFromWindow (): This method is triggered when the component is detached from a window.


14.onWindowVisibilityChanged (int): Fires when the visibility of the window that contains the component has changed

Method.


Additional two viewgroup classes are frequently overloaded methods:


1.protected void Dispatchdraw (canvas canvas): The method that the ViewGroup class and its derived classes have, which is mainly used to control the drawing and distribution of sub-view, overloading the method to change the rendering of child view, And then realize some complex visual effects.

2.protected boolean drawchild (canvas canvas, View child, Long Drawingtime): ViewGroup class and its derived classes have a method that directly controls the drawing of a specific sub-View of a Bureau , overloading the method to control a specific child view.

In the need to develop a custom view, we do not need to enumerate all of the above methods, but can be based on business needs to choose the use of the above method, below we look at a simple example program, in this sample program we only need to rewrite the OnDraw method is possible!

Example program One:

We're going to write a small ball that moves with the finger, and the idea is simply to get to the point where the user taps the screen and redraw the ball at that location:

Let's look at the procedure below:

I wrote the notes more clearly, I said briefly:

First we write a class Drawview, which is our custom control, inherited from the view

Then we first write the constructor, get to the context, here if the constructor with only the context to invoke the control in the XML error, please see my other blog post:

http://blog.csdn.net/sunmc1204953974/article/details/38101057


Below we begin to write:

Construction method Public Drawview (Context Context,attributeset attrs) {super (context,attrs);} Override OnDraw method @overridepublic void OnDraw (canvas canvas) {super.ondraw (canvas);//Create brush paint paint = new paint ();// Set the brush color Paint.setcolor (color.red);//Draw the ball canvas.drawcircle (Circlex, Circley, Circler, paint);}

Then do not forget to set the setter and getter for these data, because we need to use this view again when the monitoring can be:


Get Set method public float Getcirclex () {return circlex;} public void Setcirclex (float circlex) {This.circlex = Circlex;} public float Getcircley () {return Circley;} public void Setcircley (float Circley) {This.circley = Circley;} public float Getcircler () {return circler;} public void Setcircler (float circler) {this.circler = Circler;}

So that one of our simple custom controls is done, here's the complete code for that class:

package com.example.moveball;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.util.attributeset;import Android.view.view;public class Drawview extends view{private float CircleX = 40; private float Circley = 50;private float Circler = 15;//construction method public Drawview (Context Context,attributeset attrs) {super (con TEXT,ATTRS);} Override OnDraw method @overridepublic void OnDraw (canvas canvas) {super.ondraw (canvas);//Create brush paint paint = new paint ();// Set the brush color Paint.setcolor (color.red);//Draw the ball canvas.drawcircle (Circlex, Circley, Circler, paint);} Get Set method public float Getcirclex () {return circlex;} public void Setcirclex (float circlex) {This.circlex = Circlex;} public float Getcircley () {return Circley;} public void Setcircley (float Circley) {This.circley = Circley;} public float Getcircler () {return circler;} public void Setcircler (float circler) {this.circler = Circler;}} 

Then we just use the Android native control as usual, so let's take a look at the activity code:


Package Com.example.moveball;import Android.os.bundle;import Android.app.activity;import android.view.Menu;import Android.view.motionevent;import Android.view.view;import Android.view.view.ontouchlistener;public Class Mainactivity extends Activity {//define Drawview component Drawview Drawview = null;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);//  Create Drawview component        Drawview = (drawview) This.findviewbyid ( R.id.drawview);//  bind touch Event Drawview.setontouchlistener for Drawview component        (new Ontouchlistener () {@ Overridepublic boolean OnTouch (View arg0, motionevent event) {//Get coordinates and change the coordinates of the ball Drawview.setcirclex (Event.getx ()); Drawview.setcircley (Event.gety ());//Notifies the draw component to redraw drawview.invalidate ();//Returns True to indicate that it is executed return true;}});}      }

and layout files in XML format:


<?xml version= "1.0" encoding= "Utf-8"? ><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"    tools:context= ". Mainactivity ">    <com.example.moveball.drawview        android:id=" @+id/drawview "        android:layout_ Width= "Match_parent"        android:layout_height= "match_parent" >    </com.example.moveball.DrawView> </RelativeLayout>

Such a simple example is now in front of everyone, no matter how complex the custom control, the idea is always like this, we do not feel strange, on, as a control, we actually also to his implementation for its increase the trouble of monitoring, this is because we rewrite the way too little reason, Next talk about a frequently rewritten method:publicboolean ontouchevent (motionevent event).


The source code above already very detailed, I in the last article finally also will send a project, welcome everybody to study together!


I am also a student, write bad or have a problem place also please advice ~






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.