Android custom view-general view definition

Source: Internet
Author: User
Tags drawtext xml attribute

Android applicationsProgramView and viewgroup are used to construct user interfaces. They all inherit from view classes (or their subclasses), such as button, textview, and edittext. Styles and animation can be combined with various views to build a rich UI, which is sufficient to meet the vast majority of requirements. But sometimes we also need some special views.
To give users a distinctive experience.

Here I plan to write a long article about Android
View, the main content is: SDK partArticleTranslation (please do your best in English); custom view, AndroidSource codeAnalysis and open-source viewCodeAnalysis; interface imitation of various app applications; Use theory + code examples + practices
Guide the writing of this series of blog posts.

-- Because I have a limited level, and I often write series, this series will not write the total directory. If one day you find that this series is not updated, and I started another "big article", please throw the eggs. (But we will not refund the ticket !)

-- For the sake of foresight, the source code in this series will not provide the packaging service.

 

To put it bluntly, when we write an android program, we generally customize a class to inherit from the activity.
And rewrite the oncreate method:

@ Override
Public void oncreate (bundle
Savedinstancestate ){
Super. oncreate (savedinstancestate );

Setcontentview (R. layout. Main );
}

 

The setcontentview () method contains multiple reloads. One of them is "setcontentview (View
View) ", that is, you can directly build content through a view instance. We try to put a textview, and the code above becomes like this:

@ Override
Public void oncreate (bundle
Savedinstancestate ){
Super. oncreate (savedinstancestate );
//
Setcontentview (R. layout. Main );

Textview sayhello = new
Textview (this );
Sayhello. settext ("Hello world! I'm
Textview .");
Setcontentview (sayhello );

}

Run this code and you can see the following results on the simulator:

Is it so simple? Let's enrich it:

@ Override
Public void oncreate (bundle
Savedinstancestate ){
Super. oncreate (savedinstancestate );
//
Setcontentview (R. layout. Main );
// Textview sayhello = new
Textview (this );
// Sayhello. settext ("Hello world! I'm
Textview .");
Setcontentview (New sayhello (this ));


}
 
 
Class sayhello extends view {

Public sayhello (context)
{
Super (context );
}

@ Override
Protected void ondraw (canvas
Canvas ){
Super. ondraw (canvas );
Paint mpaint = new paint ()
;
Mpaint. settextsize (22f );
Mpaint. setcolor (color. Red );
Canvas. drawtext ("Hello
World! I'm a textview. ", 0,100, mpaint );
}
}

This time, we customized a local class sayhello to inherit from the view and override ondraw.
Method (it should be noted that the view does not have a constructor without parameters, so we can specify which constructor to implement for it ). In ondraw
In the method, we define a paint. Now you only need to understand that it has the painting function. Where should it be painted? The answer is to understand canvas as a canvas.

Now we set the mpaint font size to 22f color to red, and then write "hello" on the canvas.
World ..." And set setcontentview in oncreate as setcontentview (New
Sayhello (this ));
Finally, you should see the following in the simulator:

 

So cool! Isn't it?

No! No, the Development View in Android is not like this. It should be through
XML...

Let's modify the example.

First, we will
Class is extracted and put into a separate class file. Next, we need to add some constructors to pass parameters to the view. It is best to see the sayhello
The class should be like this:

Public class sayhello extends View
{
 
Public sayhello (Context
Context)
{
Super (context );
}

Public sayhello (context, attributeset
Attrs ){
This (context, attrs, 0 );
}
 
Public sayhello (Context
Context, attributeset attrs, int defstyle)
{
Super (context, attrs,
Defstyle );
}
 
 
@ Override
Protected void ondraw (canvas
Canvas ){
Super. ondraw (canvas );
Paint mpaint = new paint ()
;
Mpaint. settextsize (22f );
Mpaint. setcolor (color. Red );
Canvas. drawtext ("Hello
World! I'm a textview. ", 0,100, mpaint );
}
 

}

Here we will briefly explain the role of the newly added constructor. In the new constructor, attributeset is passed for the view constructor.
Attrs and INT defstyle parameters indicate that the view can
To create and accept styles to set styles. The relevant blog posts will be explained later.

Next, we will restore the oncreate method in the activity class to make it look like this:

@ Override
Public void oncreate (bundle
Savedinstancestate ){
Super. oncreate (savedinstancestate );

Setcontentview (R. layout. Main );


}

It's no different from the beginning, right.

Finally, we need to modify the layout file main and add the following XML tags to the file:

<Com. ××××. customview. sayhello

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

</COM. ××××. customview. sayhello>

(Note: XXX represents the package of the sayhello class. The full name is required here ).

Then run the program again and you should see the following results:

 

Is it very similar to what we usually define when we define a view?

You don't feel enough. What else do you need?

Well, you are very smart. Our text should be configured in XML through a certain attribute, rather than written in code!

To expose the attributes of sayhello to XML, we first need
Create an XML file named ATTS in the folder.

Add the following code:

<? XML version = "1.0"
Encoding = "UTF-8"?>
<Resources>
<Declare-styleable
Name = "sayhello">
<ATTR name = "content"
Format = "string"> </ATTR>
<ATTR name = "text_color"
Format = "color"> </ATTR>
</Declare-styleable>


</Resources>

Note that there are no smart prompts.

Then we need to modify the sayhello class. Do you still remember the attributeset? We will use it to obtain the attribute values in the XML configuration. The modified sayhello class code is as follows:

Private int mcolor;
Private string
Mcontent;

Public sayhello (context, attributeset
Attrs, int defstyle ){
Super (context, attrs, defstyle );
Typedarray
Typearray =
Context. obtainstyledattributes (attrs,
R. styleable. sayhello );
Mcolor = typearray. getcolor (R. styleable. sayhello_text_color,
0xff00ff00 );
Mcontent = typearray. getstring (R. styleable. sayhello_content );

}

@ Override
Protected void ondraw (canvas
Canvas ){
Super. ondraw (canvas );
Paint mpaint = new
Paint ();
Mpaint. settextsize (22f );
Mpaint. setcolor (mcolor );
Canvas. drawtext (mcontent,
0,100, mpaint );
}

Now you can add a value for the brother attribute in XML, but don't worry. We have to tell it the namespace.

Add: xmlns: sayhello = "http://schemas.android.com/apk/res/com.XXXX.customview" at the root of the layout File"

Sayhello
The name that can be defined for whatever you want, it will be used as the prefix of the property like Android: Layout and our: sayhello: content, the second half of the http://schemas.android.com/apk/res/ is a fixed value, next is the package name of your entire app. Do you know your package name? Catch up
Check the androidmanifest. xml file. (Note that the package name must be consistent with the package in manifest.
Otherwise, the XML Attribute cannot be found ).

Finally, we can define the desired font color content in XML:

<Com. xxxx. customview. sayhello

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content"

Sayhello: text_color = "#1212f0"
Sayhello: content = "this is a XML ATTR
View ">
</COM. xxxx. customview. sayhello>

 Run the program and you will see the following results:

 

 

This is the general definition method and process of the view.

-- Set sail.

 

 

 

// This note is copied from the macula. The image cannot be connected. Sorry.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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.