A discussion on Android custom control view

Source: Internet
Author: User

This article was reproduced from: http://www.apkbus.com/forum.php?mod=viewthread&tid=242501&extra=page%3D1



For some time, Android development will have access to custom controls, so what do you think of custom controls? Custom controls His advantage is obvious, what is the design of his ideas? What patterns do you use? I hope that after you read this article, you can publish their own custom control ideas and ideas, this post is to communicate with you. Here are some of my own views, heroes Please guide!!!


Custom View:

Here, let's look at some of the basics that are needed to customize the control view, and the common practices.


How to construct a custom view class

There are 3 main implementations of creating custom controls:


1) Inherit existing controls to implement custom controls

The main is when the control to be implemented and the existing controls are similar in many ways, by extending the existing controls to meet the requirements.


2) Implement a custom control by inheriting a layout file

Generally, this is the way to do the combined control.

Note that the OnDraw method is not used at this time, the layout file of the custom control is loaded in the constructor by Inflater, and the graphical interface of the custom control is loaded in AddView (view).

For example:

Let's say I already have a layout XML file with a TextView and a imageview in it, so you can use the layout XML just like this in the custom view construction method.


Public
MyView (context context, AttributeSet Attrs) {

Super (context, attrs);

TODO auto-generated Constructor stub

Layoutinflater inflater= (Layoutinflater) Context.getsystemservice (Context.layout_inflater_service);

Inflater.inflate (R.layout.myview, this);

imageview= (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);

textview= (TextView) Findviewbyid (R.ID.TEXTVIEW1);

}



3) Implement a custom control by inheriting the view class, using GDI to draw the component interface, which is generally not possible in either of these ways.




Two ways to customize view add properties


1) defined in the view class. Find the attribute name of the XML layout by using the AttributeSet introduced in the constructor, and then find the resource ID that corresponds to the reference to find the value.


The following is a custom two attribute text, SRC.

Layout file:


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

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent"

android:orientation= "Vertical" >



<com.apkbus.myview

Android:id= "@+id/myview1"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

text= "@string/hello_world"

src= "@drawable/logo"/>



</LinearLayout>


Property Text, Src is Read in the constructor method of the custom View class.

Java Code:


Public
MyView (context context, AttributeSet Attrs) {

Super (context, attrs);

int resourceId = 0;

int textid = Attrs.getattributeresourcevalue (null, "Text", 0);

int srcid = Attrs.getattributeresourcevalue (null, "SRC", 0);

Mtext = Context.getresources (). GetText (Textid). toString ();



}


2)PassXMLto beViewregisters a property. With theAndroidthe standard properties provided are written in the same way.

For example:

Custom attributes RequiredText,selectand theSRC, first createAttrs.xmlProperty declaration, the file is placed in theValuesdirectory.


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

<resources>



<declare-styleable name= "MyView" >

<attr name= "Text" format= "reference|string" ></attr>

<attr name= "Select" >

<enum name= "Open" value= "1" ></enum>

<enum name= "Close" value= "0" ></enum>

</attr>

<attr name= "SRC" format= "Reference|integer" ></attr>

</declare-styleable>



</resources>


Use this custom property in the layout:


<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"

xmlns:myview= "Http://schemas.android.com/apk/res/com.apkbus.myview"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent"

android:orientation= "Vertical"

>



<com.apkbus.myview

Android:id= "@+id/myview1"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

myview:text= "Www.apkbug.com"

myview:src= "@drawable/img"

myview:select= "OPEN" >

</com.apkbus.MyView>



</LinearLayout>



Description


You need to add such a line at the beginning of the layout when using a custom layout

xmlns:myview= "Http://schemas.android.com/apk/res/com.apkbus.myview"


1, MyView is a custom namespace, you can take a favorite name.



2, "Http://schemas.android.com/apk/res/com.apkbus.myview" This part of the string is by "http://schemas.android.com/apk/res/" and the application of the package name " Com.apkbus.myview "composition.




The custom view class is then read in the construction method


Public MyView (context context, AttributeSet Attrs) {

Super (context, attrs);

String pkname = "http://schemas.android.com/apk/res/" + context.getpackagename ();

int textid = Attrs.getattributeresourcevalue (Pkname, "Text", 0);

int srcid = Attrs.getattributeresourcevalue (Pkname, "SRC", 0);

int select = Attrs.getattributeintvalue (Pkname, "select", 0);

Mtext = Context.getresources (). GetText (Textid). toString ();



}



Common ways to customize view

Onfinishinflate () callback method that is called when the application is loaded from XML and used to build the interface with it


Onmeasure () Detecting the size of the view component and its subcomponents


OnLayout () When the component needs to allocate its sub-component position, large hours


Onsizechange () When the size of the component is changed


OnDraw () When the component will draw its contents


OnKeyDown when a keyboard is pressed


OnKeyUp when you release a keyboard


Ontrackballevent when a trackball event occurs


Ontouchevent when a touch-screen event occurs


Onwindowfocuschanged (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 has changed





View Design Concept:

See this little headline may feel good high-end, all to the level of the concept. In fact, with the "View Design purpose" The title is almost the meaning.

Having done this for a long time, I summed up some of the design goals.


1. The purpose of reusability

Designed to be reused in different modules and projects.



2, the purpose of flexibility

Custom view makes it easy to implement features that are not available in the system-provided controls, and greatly increases flexibility when developing projects.



3. Solution Coupling Purpose

Since custom controls are relatively independent, the coupling between the natural and other modules is also relatively low. Decoupling between modules is naturally essential.



Since there is a purpose, then how to achieve it becomes the following proposition, here I would like to talk to you about design patterns.

In front of you have already understood the realization of a custom view of the basic method, but do estimate is also crept, do not know how to concrete implementation, I call this confusion called the lack of guiding ideology.


The guiding ideology here is the design pattern, where should the business logic code be placed? Where should the UI code be placed? Where should the data store code be placed? Only three of the above questions have been identified to achieve the design purpose of the custom view.






Used in the View design mode:


The design patterns used in the view are many, the following list some of the more commonly used patterns for everyone to understand learning.


1. Set the adapter mode




For Android developers, the adapter mode is just too familiar, however, there are many applications that can be said to use the adapter mode, such as a ListView, directly or indirectly, every day.

The ListView is used to display list data, but as a list data collection there are many forms, there are arrays, there are cursor, we need the corresponding adapter as a bridge, processing the corresponding data (and can form the view required by the ListView).

It is precisely because these adapter interfaces and adapter classes are defined that our data is easily and flexibly displayed on the Adapterview implementation class.


Objective:

Adapter mode, which transforms the interface of one class into another interface that the client expects, so that the two classes that would otherwise not work together can work together.

The adapter mode is divided into class adapter mode and object adapter mode.

With respect to the class adapter pattern, because Java is single-inheritance, if you inherit a class, the other is only the interface, you need to implement the appropriate method manually.



2. Combination mode


Android in the combination of the application of the model is flooded into porridge, everywhere, that is the use of the view and ViewGroup class. In the Android UI design, almost all widgets and layout classes rely on these two classes.

The combination mode, Composite pattern, is a very ingenious pattern. Almost all object-oriented systems are applied to the combined mode.


Objective:

Combines object view and viewgroup into a tree structure to represent a "partial-whole" hierarchy (view can be a part of ViewGroup).

The combined mode makes the user consistent with the use of single object view and composite object ViewGroup.


3. MVC mode




MVC is the abbreviation for three words: Model, view, and control controller, respectively. The purpose of the MVC pattern is to realize the functional division of the web system. The model layer implements the business logic in the system. The view layer is used to interact with the user. The controller layer is a bridge between model and view that can dispatch a user's request and select the appropriate view for display, and it also interprets the user's input and maps them to the actions that the model layer can perform.



1) View layer: The general use of XML file interface description, when used can be very convenient to introduce. Of course, how you learn more about Android, you can think of Android can also use javascript+html and other ways as the view layer, of course, there is a need for Java and JavaScript communication between, fortunately, Android provides a very convenient communication implementation between them.


2) control layer (Controller): The task of Android control layer usually falls on the shoulders of many acitvity, this phrase also implies do not write code in acitivity, to through activity delivery model business Logic layer processing, Another reason for this is that the response time of Acitivity in Android is 5s, and if time-consuming operations are put here, the program is easily recycled.



3) Model: the operation of the database, the operation of the network, etc. should be processed in the model, of course, business calculations and other operations must be placed in the layer. is the binary data in the application.


4. MVP Mode



The MVP is evolved from the classic pattern MVC, where the basic ideas are interlinked: Controller/presenter is responsible for the processing of logic, model provides data, and view is responsible for the display. As a new model, there is a significant difference between MVP and MVC: In MVP, view does not use model directly, communication between them is through presenter (Controller in MVC), all interactions occur within presenter, In MVC, view reads data from the direct model rather than through the Controller.



In MVP mode, there are usually 4 elements:


(1) View: Responsible for drawing UI elements, interacting with the user (embodied as activity in Android);



(2) View interface: An interface that requires a view implementation, the view interacts with the presenter through the view interface to reduce coupling and facilitate unit testing;



(3) Model: Responsible for storing, retrieving, manipulating data (sometimes also implementing a model interface to reduce coupling);



(4) Presenter: As the intermediate link between view and model, handles the responsible logic for interacting with the user.



Core idea:

Look at so many patterns, see the head is dizzy, I have no patience to see. OK, let me explain it to you!


In fact, so many models have such a core idea, after understanding the idea of these patterns are just different realization of the same idea.



1. Physical separation

The code that handles business logic, UI layout, and data storage is physically separated, and placed in separate files.



2. External calls

Interactions between layers must be implemented through an open method of the call layer, such as the logical layer does not invoke the parent class method of the UI layer (view class), but instead calls its custom method.



3. Low coupling




At last:



Finally, I hope you will make a point of talking about your views on custom view, or the understanding of patterns. Hope you can share, if the article is wrong also hope to correct.

A discussion on Android custom control view

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.