Android Custom View Control instance

Source: Internet
Author: User
Tags getcolor stub

Android Custom view satisfies your specific needs by inheriting the view of the system and rewriting some of the methods. First let's take a look at what the methods might need to be rewritten:

Onmeasure () detects the size of the view component and its child components
OnLayout () When the component needs to allocate its child components, large hours
Ontouchevent when a touchscreen event occurs
OnDraw () When the component will be drawing its contents
OnKeyDown when you press a keyboard
OnKeyUp when you release a keyboard
Ontrackballevent when a trackball event occurs
Onsizechange () When the size of the component is changed
Onfinishinflate () callback method that is invoked after the application loads the component from XML and constructs the interface with it
Onwindowfocuschanged (Boolean) When the component gets, loses focus
Onatrrachedtowindow () When the component is put into a window
Ondetachedfromwindow () The method that is triggered when the component is detached from a window
onwindowvisibilitychanged (int): Method that is triggered when the visibility of the window that contains the component changes

The Red Callout section is the function that we often need to rewrite. The concrete implementation we give a simple example to illustrate, first on the effect chart:


A simple custom view of the circle and text following the touch event movement

To achieve the above effect we need to be divided into these steps
Create a attrs.xml under Res/values/to declare the properties of a custom view
A class that inherits view and copies the custom view of part functions
A container interface that shows custom view

Our view is called MyView and must be the same as our class filename. It has a property value, formatted as color

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>

<declare-styleable name= "MyView" >
<attr name= "TextColor" format= "Color"/>
</declare-styleable>

</resources>

2. Implement its constructor in the custom view class (for the property configuration that initially obtains view) and the replication OnDraw and ontouchevent.

public class MyView extends view{
Define brush and initial position
Paint p = new Paint ();
public float CurrentX = 50;
public float currenty = 50;
public int textcolor;

Public MyView (context context, AttributeSet Attrs) {
Super (context, attrs);
Get the attributes in the resource file, because there is only one property value, you do not have to traverse the array, directly through the R file to take out the color value
Put attributes in a resource file for easy setup and reuse
TypedArray array = context.obtainstyledattributes (Attrs,r.styleable.myview);
TextColor = Array.getcolor (R.styleable.myview_textcolor,color.black);
Array.recycle ();
}

@Override
protected void OnDraw (Canvas Canvas) {
Super.ondraw (canvas);
Draw a blue circle.
P.setcolor (Color.Blue);
Canvas.drawcircle (CURRENTX,CURRENTY,30,P);
Sets the text and color, where the color is the value of the resource file values
P.setcolor (TextColor);
Canvas.drawtext ("by Finch", currentx-30,currenty+50,p);
}

@Override
public boolean ontouchevent (Motionevent event) {

CurrentX = Event.getx ();
CurrentY = Event.gety ();
Invalidate ()//Redraw graphics
return true;

}
}

Here the idea is very simple, by constantly updating the current position coordinates and redrawing the graphics to achieve the effect, you should pay attention to the use of Typedarray must remember recycle (), or the next call will have an impact.

Unless you're no longer using Typedarray.


3. We put the myview in the Activity_main.xml, and of course we can add it to the layout through the AddView function in the code.

<?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: the prefix of the custom control = "Http://schemas.android.com/apk/res/package name (or Res-auto)", prefix: textcolor= "#ff0000". If you do not declare namespace attributes, you will


And finally, mainactivity.

public class Mainactivity extends Appcompatactivity {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
}
}

Specific view to be based on specific needs, such as we want to sideslip delete ListView We can inherit ListView, monitor Sideslip events, display the Delete button implementation function.




implementation of the Android custom view

Custom view first implements a class that inherits from view. Add a constructor for the class, override the method of the parent class, such as OnDraw, (onmeasure), and so on. If a custom view has its own attributes, you need to create a attrs.xml file in the values, define the attributes in it, and modify the code.

A simple example:

• Create a new MyView class, inherit from TextView, and add a construction method:

Package Com.example.xhelloworld;

Import Android.content.Context;

Import Android.widget.TextView;

public class MyView extends textview{

Public MyView {

Super (context);

TODO auto-generated Constructor stub

}

}

• Called again in the main activity. The method is Setcontentview (the new MyView (this));

Package Com.example.xhelloworld;

Import android.app.Activity;

Import Android.os.Bundle;

Import Android.view.Menu;

public class Newview extends activity {

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_newview);

Setcontentview (This) (new MyView);



}

@Override

public boolean Oncreateoptionsmenu (Menu menu) {

Getmenuinflater (). Inflate (R.menu.activity_newview, menu);

return true;

}

}

The results after the run are:


Such a simple custom view can be used. You can change the background color and add in the MyView class:

@Override

protected void OnDraw (Canvas Canvas) {

TODO auto-generated Method Stub

Super.ondraw (canvas);

Canvas.drawcolor (Color.Blue);

}

can be completed. Run results


The above example is simple and does not involve the addition of attributes. The scope of use is small and cannot be used in layout files. If you want to use it in a layout file, you also need to add a construction method:

Public MyView (Context Context,attributeset attrs) {

Super (context, attrs);

}

Of course, it's just a change in code, and in an XML file (Main.xml) You need to do the following:

<com.example.xhelloworld.newview

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

/>

Write the above content at least in the XML file. Where Com.example.xhelloworld.NewView is the class represented by the control that needs to be displayed. Com.example.xhelloworld is the package name of the class, Newview is the class name. This class is definitely a custom class that inherits from the view (in fact, to make ourselves write, this is nonsense ...) Can be in the project direct source code added Xxxx.java, can also be in the Libs directory of their newly added jar bag inside. If it is a class inside the jar package, the path is the path to the jar package, the class.

After completing the two steps above, you can instantiate the layout file in your code.

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

Setcontentview (This) (new MyView);

Display the same effect as above.

The following describes how to implement the property settings for a custom view. To implement the property settings for a custom view, you need to:

• Create attrs.xml files in the values directory, add attribute content

• Add the new namespace xmlns to the layout file, and you can then use namespaces to set properties for the custom space

• After setting the properties, of course you have to process them. Processing in a custom view class in a construction method

Give an example based on these three steps

First add the Attrs.xml file, in the Define attribute



<resources>

<declare-styleable name= "MyView" >

<attr name= "TextColor" format= "Color"/>

<attr name= "Textsize" format= "Dimension"/>

Declare-styleable>

Resources>

Then complete in the layout file:

Xmlns:my=http://schemas.android.com/apk/res/com.example.xhelloworld

<com.example.xhelloworld.myview

Android:layout_width= "Fill_parent"

android:layout_height= "Wrap_content"

My:textcolor= "#FFFFFFFF"

My:textsize= "22DP"

/>

Note: This step I encountered in the implementation of the error, the problem is that the display can not find attributes TextColor and textsize, this strange mistake. The workaround is that when you write my:textcolor= "#FFFFFFFF", after you write to my, press alt+/, this will automatically add an xmlns, and my path is the same, replace my with the generated one. The problem of exotic flowers is solved with the method of exotic flowers. At first I didn't know how to get it out.

Finally, add another construction method to the Myview.java and add code to handle the properties obtained from the XML

Public MyView (Context Context,attributeset attrs) {

Super (context, attrs);

Mpaint = new Paint ();

Typedarray is an array of attributes that are used to hold properties obtained by context.obtainstyledattributes

After use is complete, be sure to call the Recycle method

The name of the property is the name in Styleable + "_" + property name

TypedArray array = context.obtainstyledattributes (Attrs, R.styleable.myview);

TypedArray array = context.obtainstyledattributes (Attrs, R.styleable.myview);

int textcolor = Array.getcolor (R.styleable.myview_textcolor, 0xff00ff00); Provides a default value, where the drop is not specified

float textsize = array.getdimension (r.styleable.myview_textsize, 36);

Mpaint.setcolor (TextColor);

Mpaint.settextsize (TEXTSIZE);

Array.recycle (); Be sure to call, otherwise this setting will have an impact on your next use



}



When you are done, you have implemented a custom view, and the addition of custom view properties is handled. Now you're done with a generic custom view that inherits from views such as TextView or view, which means that the updated view is completed through the main UI thread of the program, and if it is a custom surfaceview, the implementation method is different.

After adding, there must be a lot of questions, do it yourself may not understand. Here is another explanation for the above operation.

The thing behind

How the View class is constructed:

public view (context context) is invoked when an object is created in code

public View (context, AttributeSet attrs)

The official documents are:

Constructor it called when inflating a view from XML. This was called when a view was being constructed from the XML file, supplying attributes that were the XML file . This version uses a default style of 0, so the attribute values applied are those in the context ' Theme and the Give N AttributeSet

This is roughly the method that is invoked when a view object is created from an XML file. It is obvious that the XML file is generally a layout file, is the real control when the call, and the layout file will inevitably have the property settings, such as Android:layout_width, the settings of these properties corresponding to the processing code is also completed in this method.

Two parameters

Context the "view is running in," through which it can access the current theme, resources, etc.

Attrs the attributes of the XML tag this is inflating the view

public View (context, AttributeSet attrs,int Defstyle)

Perform inflation from XML and apply a class-specific base style. This constructor of the View allows subclasses to use their own base style when they are. For example, a Button class ' s constructor would call this version of the Super class constructor and supply r.attr.buttons Tyle Fordefstyle; This allows the theme's button style to modify all of the base view attributes (into particular its background) as OK as t He Button class ' s attributes.

You don't know what you're looking for.

That's why you add the two constructs above.

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.