Android 0 Basics Section 24th: Customizing View simple use

Source: Internet
Author: User

When we meet the needs of Android-native components in our development, we should customize the view to meet these special component requirements.

I. Overview

Many of the first Android developers, for Android Custom view may be more fear, but this is the only way to master advanced, here do not do too much study, but simply understand. For higher-level content, follow-up courses will be followed, and you are welcome to share talent Show (Shareexpert) for a first-hand tutorial.

If you want to divide by type, custom view can be implemented in three ways: self-drawing controls, composite controls, and inherited controls.

    • Self-drawing controls: The content is drawn by the developer himself, and is typically done in the view's OnDraw method.

    • Combo control: It is the small controls that combine to form a new control, which is mostly a control that comes with the system. For example, the title bar control, which is commonly used in many applications, is useful for combining controls.

    • Inheriting controls: Inheriting existing controls, creating new controls, preserving the attributes of inherited parent controls, and introducing new features.

Second, the method

The basics of Android are weak, and this section is a simple way to learn about self-drawing controls. First define a subclass that inherits the view base class, and then override one or more methods of the view class. The method that can be overridden by the user is usually as follows.

  • Constructor: The overriding constructor is the most basic way to customize the view, and it will need to be called when Java code creates a view instance, or loads and constructs an interface from an XML layout file.

  • Onfinishinflate (): This is a callback method that will be called back when the application loads the component from an XML layout file and uses it to build the interface.

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

  • OnLayout (boolean, int, int, int, int): The method is called back when the component needs to allocate the position and size of its child components.

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

  • OnDraw (Canvas): The method is drawn when the component is about to draw its contents.

  • OnKeyDown (int, keyevent): Triggers the method when a key is pressed.

  • onKeyUp (int, keyevent): Triggers the method when a key is released.

  • Ontrackballevent (Motionevent): This method is triggered when a trackball event occurs.

  • Ontouchevent (Motionevent): This method is triggered when a touch screen event occurs.

  • Onfocuschanged (boolean gainfocus, int direction, Rect previouslyfocusedrect): Triggers the method when the component's focus changes.

  • Onwindowfocuschanged (Boolean): Triggers the method when the window containing the component loses or gets focus.

  • Onattachedtowindow (): This method is triggered when the component is put into a window.

  • Ondetachedfromwindow (): This method is triggered when the component is detached from a window.

  • onwindowvisibilitychanged (int): This method is triggered when the visibility of the window that contains the component has changed.

When you need to develop a custom view, the developer does not need to rewrite all of the methods listed above, but instead can rewrite some of these methods based on business needs.

Iii. examples

The following implementation of a simple counter, each click on it, the count value is added 1 and displayed.

Create a new package Com.jinyu.cqkxzsxy.android.widgetsample.view under the Src/main/java file and a new Counterview.java file with the following code:

 PackageCom.jinyu.cqkxzsxy.android.widgetsample.view;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.Rect;ImportAndroid.util.AttributeSet;ImportAndroid.view.View;/*** @ Creator Xin 鱻 * @ description Android 0 Basic primer to Master Series tutorials, Welcome to public Shareexpert*/ Public classCounterviewextendsView {//Defining Brushes    PrivatePaint Mpaint; //used to get the width and height of text    PrivateRect mbounds; //count value, the value of this control is increased by 1 per click    Private intMCount = 0;  PublicCounterview (Context context, AttributeSet attrs) {Super(context, attrs); //Initialize brush, RectMpaint =NewPaint (Paint.anti_alias_flag); Mbounds=NewRect (); //Click events for this controlSetonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (view view) {MCount++; //Redrawinvalidate ();    }        }); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas);        Mpaint.setcolor (Color.Blue); //draw a rectangle with a fill color of blueCanvas.drawrect (0, 0, GetWidth (), GetHeight (), mpaint);        Mpaint.setcolor (Color.yellow); Mpaint.settextsize (50); String text=string.valueof (MCount); //get the width and height of textMpaint.gettextbounds (text, 0, Text.length (), mbounds); floatTextWidth =mbounds.width (); floatTextHeight =mbounds.height (); //Draw a StringCanvas.drawtext (text, getwidth ()/2-TEXTWIDTH/2, GetHeight ()/2 + TEXTHEIGHT/2, Mpaint); }}

On the inside of the code does not understand also has no relationship, follow-up will be detailed study.

Create a Counterview_layout.xml file in the res/layout/directory and populate it with the following code snippet:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical">    <Com.jinyu.cqkxzsxy.android.widgetsample.view.CounterViewAndroid:id= "@+id/counter_view"Android:layout_width= "100DP"Android:layout_height= "100DP"/></LinearLayout>

Then modify the App/src/java/mainactivity.java file to load the layout file as the new Counterview_layout.xml file.

Run the program, click on the custom Count control, and you will find a value of +1 per click of the control, as shown in the effect.

Now that some of the most commonly used controls in Android development have been learned, what controls do you remember? How do you know all that? We'll start with the next issue to learn about the interface layout in Android.

Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!

This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if reproduced please note source, hereby declare!

Past period Summary share:

Android 0 Basics Introduction 1th: Android's past life

Android 0 Basics Section 2nd: Android system Architecture and application components those things

Android 0 Basics Section 3rd: Bring you up to talk about Android development environment

Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick

Android 0 Basics 5th: Use ADT bundles to easily meet the goddess

Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess

Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey

Android 0 Basics 8th: HelloWorld, the starting point for my first trip

Android 0 Basics 9th: Android app, no code can be developed

Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio

Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project

Android 0 Basics 12th: Get familiar with the Android studio interface and start selling

Android 0 Basics 13th: Android Studio Configuration optimization to create a development tool

Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era

Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing

Android 0 Basics Section 16th: Android User Interface Development overview

Android 0 Basics Section 17th: TextView Properties and Methods Daquan

Android 0 Basics Section 18th: EditText properties and how to use them

Android 0 Basics section 19th: Button usage explained

Android 0 Basics Section 20th: checkbox and RadioButton Usage Daquan

Android 0 Basics Section 21st: ToggleButton and switch usage Daquan

Android 0 Basics Section 22nd: ImageView's properties and methods Daquan

Android 0 Basics Section 23rd: ImageButton and Zoombutton use Daquan

Android 0 Basics Section 24th: Customizing View simple use

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.