Android Custom Control series three: Custom switch buttons (iii)---custom properties

Source: Internet
Author: User

Respect the original, reproduced please specify the source: http://blog.csdn.net/cyp331203/article/details/40855377


Before:Android custom Control Series II: Custom Switch button (I ) and Android custom control series three: Custom switch button (ii) continue, Today is about how to use custom properties in custom controls, there are actually two methods, one is to work with XML property resource files, and the other is the way that XML resource files are not needed; Let's take a look at each of the following:


to work with the XML property resource file, use the custom attribute:


So, for the custom controls we wrote earlier: switch buttons for example, on the basis of the previous, we have to see which properties can be customized: The background image of the button, the slider picture of the button, and the State of the button (whether it is on or off), in fact, it should be directly defined in the XML file.


Let's take a look at how we write when we don't rely on custom attributes in our code, and we can find a few lines of code in the Initview method:

Backgroundbitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); Slidebutton = Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button); Currentstate=false;

It will be found that we are directly referencing the resource file, not the way to define the properties used in the layout XML file, let's take a step-by-step look at how we can define the use of the custom attributes:


Step one: Add the Attrs.xml file to the Res/values folder


In fact, this file name does not have to be written in Attrs.xml, but according to the Android source code and also easy to see the code when others to clarify the purpose of this document, or write attrs.xml.

How to write the following, we can still look at the source of Android: Open the source folder under the \frameworks\base\core\res\res\values\attrs.xml file, we will find that there are many attr tags, There are some of our common attributes:

<attr name= "Layout_width" format= "Dimension" >

Wait, we can find a layout_width on this label

<declare-styleable name= "Viewgroup_layout" >

The declare-styleable tag contains a number of root VIEWGRUOP related properties.

And on the outermost side of this attrs.xml file, is a <resources> label


Here, we basically understand the structure of a attrs.xml file:

First, a <resources> parent tag, which can contain a declare-styleable label, in this label we define three attr label, Represent the three attributes we need to define: Button's background picture, Button's slider picture, and button state; So the remaining problem is the attr tag Span style= "FONT-FAMILY:SIMSUN; FONT-SIZE:14PX ">format stands for what it means. In fact, format represents the type of the value of this property:   

     1.reference: Refer to the resource ID in the specified theme, this type means that the value you pass can be a reference resource  
     2. String: Strings, if you want to be able to write values directly can also be used similar to "@string/test" reference resources, can be written format= "String|reference" &NBSP;
     3. Color:  
     4.boolean: boolean  
     5.dimension: Dimension value  
  & nbsp  6.float: Float type  
     7.integer: integer  
     8.fraction: Percent  
& nbsp    9.enum: Enumeration, if you provide the property can only let others choose, can not be casually passed, you could write such  
        <attr name= "Language" >  ,
                <enum name= "China" value= "1"/>  
&nbs P               <enum name= "中文版" value= "2"/>  
      &NB Sp </attr>  

10.flag: Bit or operation


Declare-styleable child elements:

Defines a Styleable object, each Styleable object is a collection of attr properties Note: The Name property here is not necessarily the same as the custom class name, just to distinguish the properties of the corresponding class.


Note: The property resource file above defines this property, as to exactly which custom view component to use the property, the property does not belong to the property resource file tube, that is, the property resource file is a public, everyone can use, but for the convenience of management, Typically a custom view property is written as a Declare-styleable collection. The properties defined by the property resource can return what effect, depending on the code implementation of the custom component


Here, our Attrs.xml file is written as follows:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Mytogglebutton" >        <attr name= "Current_state" format= "boolean"/> <attr name=        "Backgroundbitmap" format= "Reference"/ >        <attr name= "Slidebutton" format= "reference"/>    </declare-styleable></resources>



The second step: Get the corresponding value of the attribute defined in the Attrs.xml file in the class of the custom control, then assign to the variable we need to set, here is the three values of the background picture, the slider picture and the switch state.


How do you do it? Let's first give the above

Backgroundbitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); Slidebutton = Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button); Currentstate=false;

The three sentences are commented out and replaced with the following code:

/* Get declare-styleable set here */TypedArray TypedArray = Context.obtainstyledattributes (Attrs, R.styleable.mytogglebutton);/* Gets the total number of properties in this collection */int Indexcount = Typedarray.getindexcount ();/* Iterate over these properties to get the ID of the property, Then get the corresponding value by ID */for (int i = 0; i < Indexcount; i++) {/* get the corresponding id value taid*/int taid = Typedarray.getindex (i); switch (taid) {CA Se r.styleable.mytogglebutton_backgroundbitmap://drawable Turn bitmapbackgroundbitmap = ((BitmapDrawable) Typedarray.getdrawable (Taid)). Getbitmap (); Break;case r.styleable.mytogglebutton_current_state:currentstate = Typedarray.getboolean (Taid, false); Break;case R.styleable.mytogglebutton_slidebutton:slidebutton = (( bitmapdrawable) typedarray.getdrawable (Taid)). Getbitmap ();d efault:break;}}

Note is also more detailed, the basic idea is to get the corresponding Mytogglebutton the name of the Declare-styleable collection corresponding to the Typedarray object, and then according to the Typedarray object to traverse the corresponding resources and assign values.


Step three: Use a custom property in the layout file and set the property value:

<com.example.myattrsdemo.ui.myview        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "        alex:test_bitmap=" @drawable/pigs "        alex:test_id=" 1 "        alex:test_msg=" My custom attribute instance "/>

In the above code, we found that we wrote Alex: Such a header, which is actually a shorthand for the namespace, so we have to add a namespace and see how the Android namespace is written:

Xmlns:android= "Http://schemas.android.com/apk/res/android"


Here xmlns:android inside of Android, can be changed, here we will change to Alex, and then for http://schemas.android.com/apk/res/android this part, The final Android also to change, here must be changed to the entire application package name, we can go to the list file, this is Com.example.togglebutton, so the whole write down is: xmlns:alex= "/http Schemas.android.com/apk/res/com.example.togglebutton "

So here's a complete layout file written as:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    xmlns:alex=" Http://schemas.android.com/apk/res/com.example.togglebutton    " Android:layout_width= "Match_parent"    android:layout_height= "match_parent"    tools:context= "${ Relativepackage}.${activityclass} ">    <com.example.togglebutton.ui.mytogglebutton        android:id=" @+id /my_toggle_btn "        android:layout_width=" wrap_content "        android:layout_height=" Wrap_content "        android: Layout_centerinparent= "true"        alex:backgroundbitmap= "@drawable/switch_background"        alex:current_state= "True"        alex:slidebutton= "@drawable/slide_button"/></relativelayout>

At this point, a complete flow of custom attributes is completed. We can directly in the layout file to modify our custom of the three properties, we can see different effects at the time of operation, so it looks more tall ...


Two, do not need the XML resource file way to use custom attributes:


Since there is no attrs.xml, then there is no need to namespace, we directly in the above layout file add a sentence:

Test_text= "Testing does not require XML resource files to use custom properties"

Then we can get it out in Java, where we just do a simple print job:

No namespace test String attributevalue = Attrs.getattributevalue (null, "Test_text"); System.out.println (AttributeValue);

Operation Result:


According to this idea, the three attributes we defined above can be changed to a way that does not require a namespace, and it seems to be convenient. But there are actually drawbacks:

Namespaces can not be, the property name to correspond to the good, or the program will not be taken, not like there is an XML resource file in a way with a constraint.


The custom Control trilogy is now complete. Then add the content of the custom viewgroup, thanks for the attention!










Android Custom Control series three: Custom switch buttons (iii)---custom properties

Related Article

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.