Android custom control development (1), android Control

Source: Internet
Author: User

Android custom control development (1), android Control

As a creative developer or software with high requirements for uidesign, you will often encounter situations where the control provided by Android cannot meet your needs, we can only implement controls suitable for projects on our own. In addition, Android allows you to inherit existing controls or implement your own controls to optimize the interface and create a richer user experience.

 

So how to create a new control? 


This depends on the requirements.


1. You only need to extend the basic functions of the native control.Inherit and extend controls. By overwriting its event, onDraw, but always keep calling the parent class method. For example, inherit from an existing advanced control, for example, inherit a TextView.


2. You need to add the functions of several controls. In this case, you need to combine the controls to generate a new control by combining several controls. For example, in ListView, an adapter is used to organically combine multiple controls. For example, writing a control is a combination of multiple controls, which is generally a custom layout, you can use a class to inherit a layout. This layout contains multiple controls.


3. Create a new control from scratch. That is, the widget is drawn directly from the View and ViewGroup.


4. Don't forget that there is another useful <include> label. In a project, we may need to use the same layout design. If they are all written in an xml file, the code is redundant and the readability is poor, therefore, we can write code with the same layout into a single module, and then use the <include/> label to reuse the layout code.

 

Android UI interfaces are composed of View, ViewGroup, and its derived classes. Based on the android UI design principle, as a developer, we are able to develop customized components based on our own needs. View is the base class of all UI components, and ViewGroup is the container that holds these components, which is derived from View. For the general structure of the AndroidUI interface, see the following:




It can be seen that the ViewGroup as a container can contain a View as a leaf node, or a lower-level sub-ViewGroup. The sub-ViewGroup can also contain the View and ViewGroup of the leaf node on the next layer. In fact, this flexible View hierarchy can form a very complex UI layout. developers can design and develop very exquisite UI interfaces accordingly.


ViewGroup can overwrite onMeasure and onLayout to layout and process the View added to it. The function is very powerful. We will first learn how to derive custom components from the View class:

 

The View component is similar to the Panel in Swing in JAVA. It is a blank area of a rectangle without any content. For other UI controls of Android apps, It inherits the View component, and then draw it out. Therefore, we use the View subclass and override the View class method to derive our own controls.

Android custom View implementation is simple:

Inherit View, override constructor, onDraw, (onMeasure) and other functions.


If a custom View requires custom attributes, you must create attrs. xml under values. Define your attributes. Add xmlns: prefix = "http://schemas.android.com/apk/res/your custom view package path" to the xml layout file that uses the custom View ". when using custom attributes, use the prefix: attribute name, for example, my: textColor = "...... ".

 

 

Let's take a look at the methods of the View class first:

Category

Methods

Description

Creation

Constructors

There is a form of the constructor that are called when the view is created from code and a form that is called when the view is inflated from a layout file. the second form shoshould parse and apply any attributes defined in the layout file.

OnFinishInflate ()

Called after a view and all of its children has 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)

Called when this view shoshould assign a size and position to all of its children.

OnSizeChanged (int, int)

Called when the size of this view has changed.

Drawing

OnDraw (android. graphics. Canvas)

Called when the view shocould 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 is attached to a window.

OnDetachedFromWindow ()

Called when the view is detached from its window.

OnWindowVisibilityChanged (int)

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

 

You may need to override the following methods:


1. constructor, at least used to obtain Context


2. onFinishlnflate () is a callback method. When an application loads the component from an XML layout file and uses

This method will be called back after the interface is built.


3. onMeasure (int, int ):Call this method to check the size of the View component and all its child components.


4. onlayout (boolean, int, int): When the component needs to be assigned its sub-component location, size,

This method will be called back. the method called when the layout of the View class changes. This method is available for all views, viewgroups, and Their Derived classes. You can use this method to customize the layout when the layout changes, this is useful when implementing some special effects.

5. onSizeChanged (int, int): This method is called back when the size of the component is changed.


6. onDraw (canves): This method is called back when the component is about to draw its content. the method used for repainting in the View class. This method is used by all views, viewgroups, and Their Derived classes. It is also the most important method for Android UI painting. Developers can reload this method and draw their own images and effects based on the canvas parameter in the method.

7. onKeyDown (int, KeyEvent): This method is triggered when a key is pressed.


8. onKayUp (int, KeyEvent). This method is triggered 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): this parameter is triggered when the visibility of the window containing this component changes.

Method.


In addition, we add two methods that the ViewGroup class often reloads:


1. protected void dispatchDraw (Canvas canvas): A method of the ViewGroup class and its derived classes. This method is mainly used to control the rendering and distribution of sub-views. Reloading this method can change the rendering of sub-views, and then implement some complex visual effects.

2. protected boolean drawChild (Canvas canvas, View child, long drawingTime): Methods of the ViewGroup class and its derived classes. This method directly controls the rendering of a specific sub-view, you can overload this method to control a specific sub-View.

 

When developing custom views, we do not need to list all of the above methods, but can choose to use the above methods based on business needs, let's look at a simple example program. In this example, we only need to rewrite the onDraw method!

 

Example 1:

We want to write a small ball that follows the finger, the idea is very simple, as long as the user clicks the screen position, and re-draw the ball at this position:

Let's take a look at the program:

My comments are quite clear, so I will give a brief introduction:

First, we write a class DrawView, that is, our custom control that inherits

 

Then we first write out the constructor and get the Context. If the constructor containing only the Context is used, an error occurs when calling the control in xml. For details, see another blog post:

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


Let's start writing:

// Constructor public DrawView (Context context, AttributeSet attrs) {super (context, attrs);} // rewrite ondraw method @ Overridepublic void onDraw (Canvas canvas Canvas) {super. onDraw (canvas); // create Paint paint = new Paint (); // set the paint color. setColor (Color. RED); // draw the canvas ball. drawCircle (circleX, circleY, circleR, paint );}

Then do not forget to set the setter and getter of the data, because we need to add a listener when using this View:


// 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 ;}

In this way, a simple custom control is achieved. The complete code of this class is as follows:

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; // constructor public DrawView (Context context, AttributeSet attrs) {super (context, attrs);} // rewrite the ondraw method @ Overridepublic void onDraw (Canvas canvas) {super. onDraw (canvas); // create Paint paint = new Paint (); // set the paint color. setColor (Color. RED); // draw the canvas ball. 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 can use the android native control as usual. 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 {// defines DrawView component DrawView drawView = null; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create the DrawView component drawView = (DrawView) this. findViewById (R. id. drawView); // bind the Touch event DrawView to the drawView component. setOnTouchListener (new OnTouchListener () {@ Overridepublic boolean onTouch (View arg0, MotionEvent event) {// obtain the coordinates and change the drawView coordinates of the ball. setCircleX (event. getX (); drawView. setCircleY (event. getY (); // notify the draw component to re-paint the drawView. invalidate (); // return true indicates that the return true;} is executed ;}});}}

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 shown in front of everyone. No matter how complicated a custom control is, the idea is always like this. Do you think it is strange? By the way, as a control, we have to add a troublesome listener for his implementation. This is because we have too few rewrite methods. Next we will introduce you to a method that is frequently Rewritten: publicboolean onTouchEvent (MotionEvent event ).


The source code is already detailed. I will release a project at the end of the last article. You are welcome to study it together!


I am still a student. Please give me some advice on poor writing or problems ~







How to configure custom controls for android development in xml files, especially the top part of <LinearLayout>

The self-control is that you first write your control code. If you have customized a MyButton and put this MyButton class in the com. app package, then you configure the code in xml as follows:

<Com. app. MyButton
Android: layout_heigjt ...... properties/>

Hope to help you

Getting started with Android Development

Hello, you can download it from Weifeng. I hope it will help you!

Related Article

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.