Custom view for android (1)

Source: Internet
Author: User

Android provides mature and powerful UI component modeling based on two basic layout types: View and ViewGroup. First, the platform contains various pre-built views and viewgroups, known as widgets and la S. You can use them to build your UI.

Some available widgets include Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spiner, and AutoComploteTextView, ImageSwitcher, and TextSwitcher of more special users.

Some available layout s, such as LinearLayout, FramwLayout, and RelativeLayout.

If the existing widgets and layout cannot meet your requirements, you can create your own View subclass. If you only need some small adjustments to some existing widgets, you can create their subclass to override some methods.

Create a subclass of your own View to precisely control the appearance and functions of the interface elements. For custom View components, there are usually the following processing methods:

1. You can create a fully custom rendering view type. For example, the 'Volume control' knob uses 2D graphics, which is similar to a simulated electronic control.

2. You can combine a group of view components to form a new and single component. It may be similar to a ComboBox (a combination of the pop-up list and free text fields), a dual-window control selector (), and so on.

3. You can use a method similar to overwriting the EditText component and displaying it on the screen. (the effect of using the notepad tutorial is good, and a page with lines is created ).

4. You can capture other key events and process them (events) in a custom manner ).

The following describes how to create custom views and use them in applications. Some common basic practices:

1. Extend the class or subclass of the existing View.

2. Override some methods of the parent class. These methods usually start with 'on. For example, onDraw, onMeasure (), onKeyDown, and so on.

3. Use your new extension class. Once completed, your new extension class can be used in place of the base class that replaces your extension class.

Tip: the extension class is usually used as the internal class in the activity to use them, so that the parent class can easily control it. To extend its scope of use, you can also set it to public.

Fully custom components:
You can create any graphics component you want by using custom components. You can create any of your favorite appearances and actions based on your imagination (Component screen size, component processing capability.

To create a fully custom component, follow these steps:

A. inherit the View class; B. You can provide a constructor. This constructor can obtain component attributes and parameters from the XML file. You can define the attributes and parameters of your component. you can create your own event listeners, access and modify attributes, and even richer component behaviors for your components. d. this is important. You can override onMeasure () and onDraw (). By default, onDraw () does not do anything. onMeasure () sets a dimension of 100*100. E. You may need to override other methods of View or define your own methods.

  

Master the two most important aspects of a fully custom component: first, you understand the process of the component being displayed, that is, the methods of the View class that are called. The second is the definition of attributes and parameters. I think it is very important to understand:

 

The above two methods are important: onDraw and onMeasure. Let's talk about them. The onDraw () method transmits a Canvas object, which you can implement whatever you want: 2D graphics, other standard or custom components, text style, or what you want (Note: This is not suitable for 3D graphics. In this case, you must inherit SurfaceView and draw images in an independent thread, refer to GLSurfaceViewActivity sample ).
OnMeasure is complicated. Simply put, it determines the size of your component. The size determined by this statement can not only be the size of your component, but also the size of your child component (this is a problem that many people ignore ). It has two parameters, which are related to the layout_width and layout_height of your component. After you calculate the size of your component, you can use setMeasuredDimension. Why? In fact, the view calling program is: measure-> onMeasure-> setMeasuredDimension.
Here are some simple examples:
The first one is the example in samples. The source code is as follows:
LabelView. java
/**
* Example of how to write a custom subclass of View. LabelView
* Is used to draw simple text views. Note that it does not handle
* Styled text or right-to-left writing systems.
*
*/
Public class LabelView extends View {
Private Paint mTextPaint;
Private String mText;
Private int mAscent;

/**
* Constructor. This version is only needed if you will be instantiating
* The object manually (not from a layout XML file ).
* @ Param context
*/
Public LabelView (Context context ){
Super (context );
InitLabelView ();
}

/**
* Construct object, initializing with any attributes we understand from
* Layout file. These attributes are defined in
* SDK/assets/res/any/classes. xml.
*
* @ See android. view. View # View (android. content. Context, android. util. AttributeSet)
*/
Public LabelView (Context context, AttributeSet attrs ){
Super (context, attrs );
InitLabelView ();

TypedArray a = context. obtainStyledAttributes (attrs,
R. styleable. LabelView );

CharSequence s = a. getString (R. styleable. LabelView_text );
If (s! = Null ){
SetText (s. toString ());
}

// Retrieve the color (s) to be used for this view and apply them.
// Note, if you only care about supporting a single color, that you
// Can instead call a. getColor () and pass that to setTextColor ().
SetTextColor (a. getColor (R. styleable. LabelView_textColor, 0xFF000000 ));

Int textSize = a. getDimensionPixelOffset (R. styleable. LabelView_textSize, 0 );
If (textSize> 0 ){
SetTextSize (textSize );
}

A. recycle ();
}

Private final void initLabelView (){
MTextPaint = new Paint ();
MTextPaint. setAntiAlias (true );
MTextPaint. setTextSize (16 );
MTextPaint. setColor (0xFF000000 );
SetPadding (3, 3, 3, 3 );
}

/**
* Sets the text to display in this label
* @ Param text The text to display. This will be drawn as one line.
*/
Public void setText (String text ){
MText = text;
RequestLayout ();
Invalidate ();
}

/**
* Sets the text size for this label
* @ Param size Font size
*/
Public void setTextSize (int size ){
MTextPaint. setTextSize (size );
RequestLayout ();
Invalidate ();
}

/**
* Sets the text color for this label.
* @ Param color ARGB value for the text
*/
Public void setTextColor (int color ){
MTextPaint. setColor (color );
Invalidate ();
}

/**
* @ See android. view. View # measure (int, int)
*/
@ Override
Protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec ){
SetMeasuredDimension (measureWidth (widthMeasureSpec ),
MeasureHeight (heightMeasureSpec ));
}

/**
* Determines the width of this view
* @ Param measureSpec A measureSpec packed into an int
* @ Return The width of the view, honoring constraints from measureSpec
*/
Private int measureWidth (int measureSpec ){
Int result = 0;
Int specMode = MeasureSpec. getMode (measureSpec );
Int specSize = MeasureSpec. getSize (measureSpec );

If (specMode = MeasureSpec. EXACTLY ){
// We were told how big to be
Result = specSize;
} Else {
// Measure the text
Result = (int) mTextPaint. measureText (mText) + getPaddingLeft ()
+ GetPaddingRight ();
If (specMode = MeasureSpec. AT_MOST ){
// Respect AT_MOST value if that was what is called for by measureSpec
Result = Math. min (result, specSize );
}
}

Return result;
}

/**
* Determines the height of this view
* @ Param measureSpec A measureSpec packed into an int
* @ Return The height of the view, honoring constraints from measureSpec
*/
Private int measureHeight (int measureSpec ){
Int result = 0;
Int specMode = MeasureSpec. getMode (measureSpec );
Int specSize = MeasureSpec. getSize (measureSpec );

MAscent = (int) mTextPaint. ascent ();
If (specMode = MeasureSpec. EXACTLY ){
// We were told how big to be
Result = specSize;
} Else {
// Measure the text (beware: ascent is a negative number)
Result = (int) (-mAscent + mTextPaint. descent () + getPaddingTop ()
+ GetPaddingBottom ();
If (specMode = MeasureSpec. AT_MOST ){
// Respect AT_MOST value if that was what is called for by measureSpec
Result = Math. min (result, specSize );
}
}
Return result;
}

/**
* Render the text
*
* @ See android. view. View # onDraw (android. graphics. Canvas)
*/
@ Override
Protected void onDraw (Canvas canvas ){
Super. onDraw (canvas );
Canvas. drawText (mText, getPaddingLeft (), getPaddingTop ()-mAscent, mTextPaint );
}
}
Www.2cto.com
Attrs. xml
17 <resources>
18 <! -- These are the attributes that we want to retrieve from the theme
19 in app/PreferencesFromCode. java -->
30 <declare-styleable name = "LabelView">
31 <attr name = "text" format = "string"/>
32 <attr name = "textColor" format = "color"/>
33 <attr name = "textSize" format = "dimension"/>
34 </declare-styleable>
35 </resources>
Copy code
Here it customizes a View to form LabelView. It has only three attributes: text, textColor, textSize, and related methods. In the second constructor, get the xml property value for some processing. Then there is onMeasure and onDraw. There is nothing to say about them, as mentioned above.

Author slider
 
 

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.