Custom View one: Extend existing views, add new XML properties

Source: Internet
Author: User

This series is written by foreigners, dry goods! Translate out to study together. If something is wrong, don't hesitate to enlighten me!

Brief introduction

This series describes in detail how to wear pieces of Android custom view. The main topics involved are how to draw content, the principles of layout and measure, how to inherit the view group, and how to animate its child views. The first article focuses on how to extend and use existing views, and how to add unique XML attributes.

Specific tasks use a specific view

The view provided by Android is more generic and can be used anywhere. However, these common view needs to be modified during the development of the application. Most of the time the code is added to the activity so that the activity code is cluttered and affects maintenance.

Suppose you are developing an application that uses the most user-trained data. such as the total length of the user's movement, the total distance of movement and different types of movement. In order to show the data to the user in a friendly, you need to do different processing depending on the length of time the user is moving. For example, he has been exercising for 2,378 seconds, so it must have been 48 minutes. 18,550 seconds, that's definitely 5 hours and 9 minutes.

Create a custom view

The best way to deal with the problem above is to define a view. This view includes the ability to handle the above time. Let's create a custom view: DurationTextView .

class DurationTextView : TextView { constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) { }}

TextViewAs with the other view, there are three constructors: one is only needed Context , one is the two arguments that are given above Context AttributeSet , and one that requires a style other than these two parameters. In general, the construction method given above can be satisfied. The view defined above is used in the layout below.

< Demo.customview.customviewdemo.views.durationtextview android:id= "@+id/ Duration_view " android: Layout_width= "match_parent"  android:layout_height=< Span class= "St" > "wrap_content"  />            

Note that the full name of the custom view needs to be given here.

Add presentation logic

Now this view is not much TextView different from the standard. We add a property for this view duration to set and read the duration value.

var Duration:FloatGet () = _durationSetValue) {_duration =Valuevar durationinminutes:Int = Math.Round (_duration/60)var hours:Int = durationinminutes/60var minutes:Int = durationinminutes%60var Hourtext:String =""var Minutetext:String =""if (Hours >0) {Hourtext ="$hours ${if (Hours = = 1)"Hour"Else" hours"}" }if (Minutes >0) {Minutetext = "$minutes ${if (minutes = = 1)" minute "else" Minutes "}"} if (hours = 0 && minutes = = 0) {minutetext =  " Less than 1 minute "} var durationtext = Text_template.< Span class= "Hljs-keyword" >format (Hourtext, Minutetext) text = durationtext}companion span class= "kw" >object {val text_template =  "Duration:%s%s"}            

This method accepts a Float type of parameter, the number of seconds of the training time. It then converts the number of seconds into a user-friendly literal value using the conversion logic above. TextViewthe text that is assigned to the last value. The logic of the conversion is very simple, which is to turn the number of seconds into minutes and finally to the hour and minute values. Minutes and hours if the unit is greater than 1 is displayed as minutes and hours, equals 1 when the time is minute and hour.

Use it.

Now it's time to try the effect. Add the following code to the activity's onCreate() method:

Override FunOnCreate (savedinstancestate:Bundle?) {Super.OnCreate (Savedinstancestate)Setcontentview (R.Layout.Activity_main)var durationTextView1 =Findviewbyid (R.Id.DURATION_VIEW1)AsDurationtextview DurationTextView1.duration = 2378.0f var durationTextView2 = findviewbyid (r.id . duration_view2) as durationtextview DurationTextView2.duration = 3670.0f var durationTextView3 = findviewbyid (r.id. duration_view3) as durationtextview DurationTextView3.duration = 18550.0f}       

Running results such as:

It looks pretty good.

adding XML attributes

If we can add a method to this view to set the template for the text presentation, just like setting duration. However, this template does not really want to duration the same as the need for regular settings, more is a similar to the existence of constant. So for adding a method, it is more appropriate to add an XML attribute.

First add the values/attrs.xml file, and the XML attribute is defined in this file. We just need to add a string type with the name of the template property. After adding the attrs.xml file looks like this:

<Resources><Declare-styleable name= " Templatetextview "> <attr name=< Span class= "Hljs-tag" > "template"  format=" string "  />  </declare-styleable></ RESOURCES>              

We have declared a declare-styleable node named templatetextview . The name can be arbitrary, but it's best to use it in which view it's called. This is called Templatetextview because later this XML attribute is used with many other custom view. Let's see how this property is used.

<LinearLayout Xmlns:android="Http://schemas.android.com/apk/res/android" xmlns:app="Http://schemas.android.com/apk/res-auto" xmlns:tools="Http://schemas.android.com/tools" Android:layout_width="Match_parent" android:layout_height="Match_parent" android:orientation="Vertical" tools:context="Demo.customview.customviewdemo.MainActivity"><Demo.customview.customviewdemo.Views.DurationTextView Android:id="@+id/duration_view1" Android:layout_width="Match_parent" android:layout_height="Wrap_content" android:text= "customized" android:textsize="20sp" app:template="%s was Spent running " /> <!--......--></linearlayout>    

When you add a line in the format code (shortcut key ctrl+alt+l, or cmd+alt+l) LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto" , the sentence declares a namespace so that the app can understand the attributes we just added in the layout of the custom view. Of course you need to prefix the app specified in this declaration: app:template="%s was spent running" .

Now we need to read and apply the newly added property values in the code. First, you add a var template:String? = null property that is ready to receive the parsed string template.

var attributes = context.obtainStyledAttributes(attributeSet, R.styleable.TemplateTextView)template = attributes.getString(R.styleable.TemplateTextView_template)if (template == null || !(template?.contains("%s", ignoreCase = true) ?: false)) { template = TEXT_TEMPLATE}attributes.recycle()

The first line uses a AttributeSet type parameter attributeSet that contains all of the properties defined in the attrs.xml file. obtainStyledAttributes()The method mainly does two things:

    1. Filter all the custom attributes and associate the definitions of these attributes with the given values.
    2. Returns the combination of attributes that you specified in the second argument.

R.styleable.TemplateTextViewis a property array of our own definition, there is only one element. R.styleable.TemplateTextView_templateis the element in our custom attribute array called template . Then we use the typed array to get the value of this property. If the template is not set, or if the template does not contain the %s that handles the string, it is replaced with the default text template we defined earlier.

However, it is important to note that the Typedarray object is recycled, regardless of whether or not a property value is obtained attributes.recycle() .

Up and down two sets different template, the middle of not set, run to see how the effect of the modified:

For most Android view XML attributes, there is a corresponding way to set the corresponding value by code. Whether you need to do this for a custom view depends largely on how you intend to use it. There's nothing wrong with adding a method.

The next article outlines how to draw the contents of a view and customize a view that displays a line chart.

Custom View one: Extend existing views, add new XML properties

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.