Android custom controls-custom properties, android Custom Controls

Source: Internet
Author: User

Android custom controls-custom properties, android Custom Controls

Reprinted please indicate the source:Http://blog.csdn.net/allen315410/article/details/39343401

When customizing android components, apart from using Java to build components, we sometimes need to declare some "attributes" for the project to use, so what is the component property?

For example, when creating a TextView in the list file, this is the android: layout_width = "wrap_content" android: layout_height = "wrap_content" of TextView, and so on, which are the attributes of components, textView is a component provided by the android system. Its Attributes are also provided by the android system. For more information, see the android source code. Here is an example of the source code of android2.3. The path is
/Frameworks/base/core/res/values/attrs. xml, which defines the attributes of all android system components.

When customizing components, you can use the android system to provide us with good properties, as well as custom properties. The main steps for customizing attributes are as follows:
1. Declare attributes in the attrs. xml fileSuch:
<Declare-styleable name = "MyToggleBtn"> // name of the famous property set, that is, the control to which these attributes belong. <Attr name = "current_state" format = "boolean"/> // The current_state attribute is of the boolean type. <attr name = "slide_button" format = "reference"/> // fame the format of the property slide_button is reference </declare-styleable>
All format types
Reference
Color
Boolean Value
Dimension size value
Float floating point value
Integer value
String
Enum enumerated Value

Ii. Use in layout files: namespace must be known before use, xmlns: example = "http://schemas.android.com/apk/res/com.example.mytogglebtn"
Note: xmlns is short for XML name space;
Example can be any write character
Http://schemas.android.com/apk/res/ This is a fixed android format;

Com. example. mytogglebtn the package name of this application, such as the same 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" />

3. parse attributes in codeThe Code is as follows:

TypedArray ta = context. obtainStyledAttributes (attrs, R. styleable. MyToggleBtn); // TypeArray obtained by attrs

The above is the general procedure for creating custom properties. Next, I will create a Demo of a custom control to learn about custom attributes.

First, you must create a custom control and inherit the View. Create the attrs. xml file in the res/values folder of the project:

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <! -- Declare an Attribute-level name --> <declare-styleable name = "MyView"> <! -- Declare an attribute, integer --> <attr name = "test_id" format = "integer"/> <! -- Declare an attribute, string --> <attr name = "test_msg" format = "string"/> <! -- Declare an attribute, reference, and reference the resource id --> <attr name = "test_bitmap" format = "reference"/> </declare-styleable> </resources>
Then, reference the custom control MyView in the layout file.

<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 inherits the View, you must rewrite the View constructor. The View has three constructor methods. Let's first look at the constructor with a parameter in the rewrite:

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}}
After running the project, the project crashes immediately and the error is clear:

06:52:24 09-17. 389: E/AndroidRuntime (1563): Caused by: java. lang. noSuchMethodException: <init> [class android. content. context, interface android. util. attributeSet]

Indicates that no constructor with two parameters is found. Therefore, the custom attribute must be rewritten to another constructor of the parent class. Modify the following:

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, attrs);int count = attrs.getAttributeCount();for (int index = 0; index < count; index++) {String attributeName = attrs.getAttributeName(index);String attributeValue = attrs.getAttributeValue(index);System.out.println("name:" + attributeName + "  value:" + attributeValue);}}}
The output is as follows:


AttributeSet: the parsed results of the layout file XML are encapsulated as AttributeSet objects. Raw data is stored, but the data is simply processed.

The constructor will help us return the parsing result of the XML layout file. How can we get this result? 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, find a class TypeArray that is very relevant to the property. Next, I will also get the class TypeArray In the constructor of the custom control:

If you look at the source code of TypeArray, you will find that TypeArray does not inherit any classes (except objects). That is to say, TypeArray is equivalent to a tool class through context. the obtainStyledAttributes method transmits the AttributeSet and attribute types. For example, AttributeSet is equivalent to raw material, and the attribute type is equivalent to drawing and context. obtainStyledAttributes is equivalent to the properties processed by the processing factory into the object and 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); // obtain attributes in R. 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 ;}}}}

The following are the methods in the TypeArray class. No comments are provided here. For details, see:


When these set attribute values are obtained in the constructor, the value can be taken out and processed in the code.

The previous blog mentioned the Android custom control, which is similar to the ios sliding switch button. Next, we need to customize the properties for the sliding switch button condition. I am not familiar with the Demo of the previous blog, you can go to your browser and click here on my previous blog.Android custom control-ios-like sliding button

First, follow the steps described above to create an attribute file attrs. xml in the res/values directory:

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <declare-styleable name = "MyToggleBtn"> <! -- Sliding button background image --> <attr name = "switchBG" format = "reference"/> <! -- Slide block image --> <attr name = "slideBg" format = "reference"/> <! -- Set the current status --> <attr name = "currState" format = "boolean"/> </declare-styleable> </resources>
Then, set the custom attributes in the acticity_main.xml layout file that references the custom control. Remember, before referencing these attributes, you must first reference the namespace:

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

Here: mytogglebtn is an arbitrary name, which has no mandatory requirements. However, when referencing attributes in the control, it must be consistent. Do not write an error.

Com. example. slidebutton is the package name of the project. Do not make a mistake. Otherwise, the property file cannot be found.

<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 component class constructor to parse the attribute set into TypeArray, get the relevant attribute values from TypeArray, and use them to initialize custom control, the main code is as follows:

Public SlideButton (Context context, AttributeSet attrs) {super (context, attrs); // obtain the custom attribute TypedArray ta = context. obtainStyledAttributes (attrs, R. styleable. myToggleBtn); int count = ta. getIndexCount (); for (int I = 0; I <count; I ++) {int itemId = ta. getIndex (I); // obtain the Id of an attribute. switch (itemId) {case R. styleable. myToggleBtn_currState: // sets the current button state currentState = ta. getBoolean (itemId, false); break; case R. styleable. myToggleBtn_switchBG: // set the background image int backgroundId = ta. getResourceId (itemId,-1); if (backgroundId =-1) throw new RuntimeException ("the resource is not found, set the background image"); switchBG = BitmapFactory. decodeResource (getResources (), backgroundId); break; case R. styleable. myToggleBtn_slideBg: // sets the button image int slideId = ta. getResourceId (itemId,-1); if (slideId =-1) throw new RuntimeException ("the resource is not found, please set the button image"); slideButtonBG = BitmapFactory. decodeResource (getResources (), slideId); break; default: break ;}}}

As shown in the preceding figure, custom attributes are actually very simple. In the constructor method, the obtained property set is processed into a TypeArray object, and the property id is obtained through this object, retrieve the values corresponding to each property using the id (after all, the layout file XML in Android is also in the key-value format), and finally obtain the property value (control user-defined data) initialize to the custom control, so that a complete custom control is complete. This complete custom control method is rarely used, because when developing a custom control, you can set the required data directly in the Java code, which is much more convenient. However, in a specific situation, if the data of the developed control is uncertain, or the developed control needs to be provided to others for preference settings, such custom attributes become useless.


Download the source code here



How do android custom controls customize attributes?

You can define attributes in attrs. xml. However, it is better to write such custom things in the Code and load them dynamically to facilitate control.

C # custom properties of Custom Controls

Well, don't do that. It will be annoying. This is something that the project team has a dedicated person to do.
--------------------------------------------
The Design of custom controls can be set in many ways. For more information, see
Using System. ComponentModel;
Using System. ComponentModel. Design;
Using System. Windows. Forms. ComponentModel;
Using System. Drawing;

/// <Summary>
/// </Summary>
/// <Example>
/// </Example>
/// <Remarks>
/// </Remarks>
[DefaultEvent ("EventName")]
[DefaultProperty ("PropertyName")]
[Description ("Description")]
[DesignerCategory ("xXx")]
[ToolboxBitmap (typeof (System. Windows. Forms. Button)]
[ToolboxItem (true)]
Public class TriStateButton: System. Windows. Forms. Control
{
[Browsable (true)]
[Category ("Common")]
[DefaultValue ("TriStateButton1")]
[Description ("TriStateButton Description")]
[EditorBrowsable (EditorBrowsableState. Always)]
Public string ButtonName {get; set ;}
}

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.