"Android Notes" View controls with custom attributes

Source: Internet
Author: User

Custom View controls or composite controls are often required in development, and some controls may require some additional configuration. For example, to customize a title bar, you may need to customize a different length of the title bar depending on the size of the phone, or more commonly you need to configure the background of the title bar, you will consider the extension of the view you write, usually, we can add some setxxx methods for this custom title bar For external invocation, setting its color, length and other properties. But we all know that when using system controls, most of the time we don't need to configure the controls in code, but simply configure the control's width, height, color, and so on in the layout file, and the benefits decouple The UI from the business logic to make the code clearer . Customizing the View control with attributes is very easy to implement, as described in the following steps:

1. Write the Attrs property file . Android does not attrs.xml by default, we need to manually create a new file in the values directory. File root node is the resources, child nodes called declare-styleable, such as the following is a attrs file:

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

This property file provides a set of properties called MyView, with two attributes, one radius for the integer type, and another color of type color, which will be used in the custom view in the future. 2. Write a custom view. This presumably everyone is not unfamiliar, I here is a simplest custom view, draw a circle.
Package Com.example.attributedemo;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.paint.style;import Android.util.attributeset;import Android.view.view;public class MyView extends View{private Paint mpaint = null;/** * Round color */private int mcolor;/** * Circle radius */private int mradius;/** * default color */private Stati c final int default_color = color.red;/** * Default radius */private static final int default_radius = 50;public MyView (Context cont EXT) {super (context); Mcolor = Default_color;mradius = Default_radius;init ();} Public MyView (context context, AttributeSet Attrs) {Super (context, attrs, 0); GetConfig (context, attrs); init ();} /** * Initialize brush */private void init () {mpaint = new Paint (); mpaint.setstrokewidth (1); Mpaint.setstyle (Style.fill); Mpaint.setcolor (Mcolor);} /** * Get configuration information from XML */private void GetConfig (Context context,attributeset attrs) {//typedarray is an array container for storing property values Typedarray ta =Context.obtainstyledattributes (attrs,r.styleable.myview); Mradius = Ta.getint (R.styleable.myview_radius, DEFAULT_ RADIUS); Mcolor = Ta.getcolor (R.styleable.myview_color, Default_color);//after use, recycle container ta.recycle ();} @Overrideprotected void OnDraw (canvas canvas) {//Draw a circle Canvas.drawcircle (Mradius, Mradius, Mradius, Mpaint);}}

The logic in this is very simple, it is important to note that this getconfig method, the method inside a Typedarray object is constructed through the context and AttributeSet, which is a set of container, which is a custom attribute and corresponding value. The object exposes a series of get methods to the outside world to get different types of property values. Typedarray must be recycled after use
3. Write the layout file, using the custom view above.
Relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:myview= "http// Schemas.android.com/apk/res/com.example.attributedemo "    android:layout_width=" Match_parent "    android: layout_height= "Match_parent" >    <com.example.attributedemo.myview        android:layout_width= "200DP"        android:layout_height= "200DP"        myview:radius= "myview:color="        #bc9300 "/></ Relativelayout>

It is important to note that in order to use custom properties, you must first add a namespace, otherwise Android does not recognize these custom attributes. The generic rule for named controls is in Xmlns:[attrsDeclare-Styleable's name]= "http://schemas.android.com/apk/res/Package Name ", 4. Locate the layout through Setcontentview in the activity.
Display effect:

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.