Android Custom Controls--Custom properties

Source: Internet
Author: User
Tags set background

Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/39343401

When we were customizing the Android components, we sometimes needed to assert that some "properties" were available to the project, in addition to Java building the components, so what are the properties of the components?

For example, in the manifest file, when creating a textview, it is necessary to develop TextView android:layout_width= "wrap_content" android:layout_height= "wrap_content "And so these are the components of the properties, TextView is the Android system for us to provide good components, its properties are also available for us Android system." Details of the Android source code, I here example android2.3 source, the path is
/frameworks/base/core/res/res/values/attrs.xml, this attrs.xml defines the properties of all Android system components.

When we customize the components, we can also customize the properties in addition to the good properties available to us using the Android system. The main steps of a custom property are as follows:
I. Declaring attributes in the Attrs.xml fileSuch as:
<declare-styleable name= The name of the "mytogglebtn" >            //Reputation property set, that is, which control the properties belong to. <attr name= "Current_state" format= "boolean"/>   //Reputation Property current_state format is Boolean type <attr name= "Slide_ Button "format=" Reference "/>   
All the format types
Reference Reference
Color Color
Boolean Boolean value
Dimension dimension Value
Float Floating point value
Integer Integer value
String String
Enum Enumeration values

second, in the layout file use: Before using the namespace must be known,xmlns:example= "Http://schemas.android.com/apk/res/com.example.mytogglebtn"
Description: xmlns is the abbreviation for XML name space;
Example can be any write character
Http://schemas.android.com/apk/res/this for Android fixed format;

COM.EXAMPLE.MYTOGGLEBTN the package name for this app, as consistent in the manifest configuration file.

Layout file:

<com.example.mytogglebtn.mytogglebutton    xmlns:example= "http://schemas.android.com/apk/res/ Com.example.mytogglebtn "    android:layout_width=" wrap_content "    android:layout_height=" Wrap_content     " example:slide_button= "@drawable/slide_button"/>

third, in the code to parse the attributes , the code is as follows:

TypedArray ta = context.obtainstyledattributes (attrs, R.STYLEABLE.MYTOGGLEBTN);//Attrs obtained Typearray

These are the approximate steps to create a custom property. Below, I'm going to create a demo of a custom control to learn about the knowledge points of the custom properties.

First, you need to create a custom control and inherit the view. Create the Attrs.xml file under the project's Res/values folder:

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <!--declaring attribute-level names--    < Declare-styleable name= "MyView" >        <!--Declare a property, integer--        <attr name= "test_id" format= "integer"/>        <!--Declare a property, string--        <attr name= "test_msg" format= "string"/>        <!--declares a property, reference, reference resource ID--        <attr name= "Test_bitmap" format= "reference"/>    </declare-styleable></resources>
Then, in the layout file, refer to this custom control MyView

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    xmlns:example=" Http://schemas.android.com/apk/res/com.example.myattrs    " Android:layout_width= "Match_parent"    android:layout_height= "match_parent" >    < Com.example.myattrs.MyView        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:layout_centerinparent= "true"        example:test_bitmap= "@drawable/ic_launcher"        example:test_msg = "@string/app_name"/></relativelayout>

Since the created custom component MyView is inherited from the view, it must be constructed with a carbon-copy view, with three constructs in the view, and a first look at the method of constructing a parameter of the replication band:

Package Com.example.myattrs;import Android.content.context;import Android.view.view;public class MyView extends View { Public MyView (Context context) {super (context);//TODO auto-generated constructor stub}}
Run the project, then the project immediately collapsed, the error is clear:

09-17 06:52:24.389:e/androidruntime (1563): caused by:java.lang.NoSuchMethodException: <init> [Class Android.content.Context, Interface Android.util.AttributeSet]

Indicates that a construction method with two parameters has not been found, so it is necessary to know that the custom attribute must be replicated by another constructor of the parent class, modified as follows:

Package Com.example.myattrs;import Android.content.context;import Android.util.attributeset;import Android.view.view;public class MyView extends View {public MyView (context context, AttributeSet Attrs) {Super (context, at TRS); int count = Attrs.getattributecount (); for (int index = 0; index < count; index++) {String AttributeName = attrs.ge Tattributename (index); String AttributeValue = attrs.getattributevalue (index); System.out.println ("Name:" + attributename + "  value:" + AttributeValue);}}}
The printing results are as follows:


AttributeSet: The result of parsing the layout file XML, encapsulated as a AttributeSet object. The raw data is stored, but the data is simply processed.

This constructor helps us return the parsing result of the layout file XML, and get the result, what should we do? Next, let's take a look at how the view class handles this:

Public View (context context, AttributeSet attrs) {This        (context, attrs, 0);    }
Public View (context context, AttributeSet Attrs, int. defstyle) {This        (context);        TypedArray a = Context.obtainstyledattributes (Attrs, Com.android.internal.r.styleable.view,                defstyle, 0);
So, to find a class typearray that is relevant to the property, then I'll get the Typearray class on the constructor of the custom control:

Look over the Typearray source will find that Typearray is not inheriting any class (except object), that is, typearray equivalent to a tool class, Through the Context.obtainstyledattributes method, the types of AttributeSet and attributes are passed in, such as attributeset equivalent to raw materials, attribute types equivalent to drawings, context.obtainstyledattributes phase When processing in the processing plant into the properties of the object, encapsulated into the Typearray class.

Package Com.example.myattrs;import Android.content.context;import Android.content.res.typedarray;import Android.util.attributeset;import Android.view.view;public class MyView extends View {public MyView (context context, AttributeSet attrs) {Super (context, attrs);  TypedArray ta = context.obtainstyledattributes (attrs, r.styleable.myview); int count = Ta.getindexcount (); for (int i = 0; i < count; i++) {int itemId = Ta.getindex (i); System.out.println ("ItemId::" + itemId); Gets the attribute in the R.java file of Idswitch (itemId) {case R.styleable.myview_test_bitmap:int bitmapid = Ta.getresourceid (itemId, 100); System.out.println ("Bitmapid::" + bitmapid); break;case r.styleable.myview_test_id:int test_id = Ta.getinteger (itemId , 10); System.out.println ("test_id" + test_id); break;case r.styleable.myview_test_msg:string test_msg = ta.getstring (itemId ); System.out.println ("Test_msg::" + test_msg); break;default:break;}}}

Here is the method in the Typearray class, which does not write the comment, see the name to know:


When you get these set property values in the constructor method, the values are taken out and processed in the code.

The previous blog mentions the Android custom control-imitation ios sliding switch button, next, for this sliding switch button condition custom properties, not familiar with the previous blog demo, you can go to the browser for my previous blog, click here Android custom Control- -Imitation iOS slide switch button

First, follow the steps described above to create a property file Attrs.xml in the Res/values directory:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "MYTOGGLEBTN" >        <!--slide button background image--        <attr name= "SWITCHBG" format= "Reference"/> <!--slider picture--        < attr name= "SLIDEBG" format= "reference"/>        <!--set Current state--        <attr name= "Currstate" format= "Boolean "/>    </declare-styleable></resources>
Then, set the custom properties on the layout file acticity_main.xml that references the custom control, and remember that the namespace must be referenced before referencing these properties:

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

Where:mytogglebtn is arbitrary name, there is no mandatory requirements, but in the control to refer to the property, should be consistent, do not write wrong

Com.example.slidebutton is the project's package name, do not make a mistake, or cannot find the property file

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    xmlns:mytogglebtn=" Http://schemas.android.com/apk/res/com.example.slidebutton "    android:layout_width= "match_parent"    android:layout_height= "match_parent" >    < Com.example.slidebutton.view.SlideButton        android:id= "@+id/slidebutton"        android:layout_width= "Wrap_ Content "        android:layout_height=" wrap_content "        android:layout_centerinparent=" true "        mytogglebtn: Currstate= "false"        mytogglebtn:slidebg= "@drawable/slide_button_background"        mytogglebtn:switchbg= "@ Drawable/switch_background "/></relativelayout>
With the above steps, we can customize the constructor method of the component class, parse the property set into Typearray, get the related property value from Typearray, and use it to initialize the custom control, the following is the main code:

Public Slidebutton (context context, AttributeSet Attrs) {Super (context, attrs);//Get custom properties Typedarray TA = Context.obtainstyledattributes (Attrs, r.styleable.mytogglebtn); int count = Ta.getindexcount (); for (int i = 0; i < Coun T i++) {int itemId = Ta.getindex (i); Gets the ID value of a property switch (itemId) {case r.styleable.mytogglebtn_currstate://Sets the state of the current button Curr Entstate = Ta.getboolean (ItemId, false); Break;case R.STYLEABLE.MYTOGGLEBTN_SWITCHBG://Set button background image int Backgroundid = Ta.getresourceid (ItemId,-1); if (Backgroundid = =-1) throw new RuntimeException ("Resource not found, set background map"); SWITCHBG = Bitmapfactory.decoderesource (Getresources (), backgroundid); Break;case R.STYLEABLE.MYTOGGLEBTN_SLIDEBG:// Set button picture int slideid = Ta.getresourceid (itemId,-1); if (SlideID = =-1) throw new RuntimeException ("Resource not found, please set button picture"); SLIDEBUTTONBG = Bitmapfactory.decoderesource (Getresources (), slideid); break;default:break;}}}

As you can see from the above, custom properties are actually very simple. In the construction method, the acquired attribute set is processed into a Typearray object, through which the ID of the property is taken out, and the value of each attribute is taken out by ID (after all, the layout file XML under Android is also in key-value form). Finally, the obtained property value (control user-defined data) is initialized to the custom control, so that a complete custom control is completed. This complete custom control approach is not very common, as it is much easier to create a custom control that requires data to be set directly in the Java code. However, in a specific situation, this custom property is not available if you are developing a control with some data that is not deterministic, or if the control you are developing needs to provide to other people for preference settings.


Please download the source code here


Android Custom Controls--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.