Simple example of Android custom control (view)

Source: Internet
Author: User

    • Android Custom View inherits the system's view and overrides some of the methods to meet its specific needs. Let's start by looking at what methods may need to be rewritten:
     onmeasure () Detecting the size of the view component and its subcomponentsonlayout () when the component needs to allocate its sub-component position, large hoursOntouchevent When a touch-screen event occursOnDraw () when the component will draw its contentsOnKeyDown When a keyboard is pressedOnKeyUp When you release a keyboardOntrackballevent when a trackball event occurs Onsizechange () the Onfinishinflate () callback method when the size of the component is changed, and the method that is called after the application is loaded from XML and used to build the interface with it ONWINDOWF    Ocuschanged (Boolean) When the component gets, loses focus Onatrrachedtowindow () when the component is placed in a window Ondetachedfromwindow () The method that is triggered when the component is detached from a window onwindowvisibilitychanged (int): The method that fires when the visibility of the window that contains the component is changed the part of the red callout is the function that we often need to override. The concrete implementation we give a simple example to illustrate, first: circle and text follow touch event move a simple custom view
    • To achieve the above effect, we need to divide these steps roughly.
      • Create a attrs.xml under Res/values/to declare the properties of your custom view
      • A class of custom view that inherits the view and the partial function of the replication
      • A container interface for displaying custom view
    1. Our view is called MyView and must be the same as our class file name. It has a property value in the form of color

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "MyView" >        <attr name= "TextColor" format= "color"/>    </declare-styleable>        </resources>

2. Implement its constructors (for initial view property configuration) in the custom view class and the replication OnDraw and ontouchevent.

 Public classMyViewextendsview{//defining brushes and initial positionsPaint p =NewPaint ();  Public floatCurrentX = 50;  Public floatCurrentY = 50;  Public intTextColor;  PublicMyView (Context context, AttributeSet attrs) {Super(context, attrs); //get the property in the resource file, because there is only one property value, do not iterate through the array, take out the color value directly from the R file//Put attributes in a resource file for easy setup and reuseTypedArray array =context.obtainstyledattributes (Attrs,r.styleable.myview); TextColor=Array.getcolor (R.styleable.myview_textcolor,color.black);    Array.recycle (); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); //draw a blue circle.P.setcolor (Color.Blue); Canvas.drawcircle (Currentx,currenty,30, p); //set the text and color, where the color is the value inside the resource file valuesP.setcolor (TextColor); Canvas.drawtext ("By Finch", currentx-30,currenty+50, p); } @Override Public Booleanontouchevent (Motionevent event) {CurrentX=Event.getx (); CurrentY=event.gety (); Invalidate ();//Redraw a graphic        return true; }}

Here the idea is very simple, by constantly updating the current position coordinates and redrawing the graphics to achieve the effect, it is important to note that after using Typedarray must remember recycle (), otherwise the next call will have an impact.

Unless you don't use Typedarray again.

3. We put MyView in the activity_main.xml, of course, in the code through the AddView function added to the layout.

<?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" Xmlns:myview= "Http://schemas.android.com/apk/res-auto"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Finch.scu.cn.myview.MainActivity" > < finch.scu.cn.myview.myView android:layout_width= "Match_parent"Android:layout_height= "Match_parent"myview:textcolor= "#ff0000"/></relativelayout>

Here xmlns: prefix of custom control = "Http://schemas.android.com/apk/res/package name (or Res-auto)", prefix: textcolor= "#ff0000". If you do not declare the namespace attribute, you will

And finally the mainactivity.

 Public class extends appcompatactivity {    @Override    protectedvoid  onCreate (Bundle Savedinstancestate) {        super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    }}

    • Specific view to be based on specific needs, such as we want to slide off the listview we can inherit the ListView, listen to the slide event, display Delete button implementation.

Simple example of Android custom control (view)

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.