Android custom controls Series 3: Custom switch buttons (3) --- custom properties, android controls
Respect Original, reprinted please indicate the source: http://blog.csdn.net/cyp331203/article/details/40855377
Before receiving:Android custom control series 2: Custom switch button (1)AndAndroid custom control Series 3: Custom switch button (2)To continue, we will talk about how to use custom attributes in custom controls. In fact, there are two methods: one is to use XML Attribute resource files, the other method is that XML resource files are not required. Let's take a look at the following:
1. Use custom attributes in combination with the XML property resource file:
For the custom control we wrote earlier: the switch button is used as an example. Based on the previous settings, let's take a look at the attributes that can be customized: the background image of the button, the slider image of the button and the button status (ON or OFF) can be directly defined in the xml file.
Let's take a look at how we wrote the code without relying on Custom Attributes. We can find the following 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;
We will find that we are directly referencing the resource file, rather than using the defined attributes in the layout xml file. Next we will take a step-by-step look at how we can define the use of the custom attributes:
Step 1: add the attrs. xml file to the res/values folder.
In fact, this file name does not have to be written as attrs. xml, but it is written as attrs. xml based on the android source code, which is easy for others to check the code.
How to write the following code? For more information, see the android source code: open \ frameworks \ base \ core \ res \ values \ attrs in the source code folder. in the xml file, we will find that many attr tags are defined here, and there are some common attributes in them:
<Attr name = "layout_width" format = "dimension">
Wait. We can also find
<Declare-styleable name = "ViewGroup_Layout">
The declare-styleable tag contains many attributes related to the root ViewGruop.
The outmost part of the attrs. xml file is a <resources> label.
Here, we basically understand the structure of an attrs. xml file:
First, you need a <resources> parent tag, which can contain a declare-styleable tag. In this tag, we define three attr tags, three attributes that need to be defined: the background image of the button, the slider image of the button, and the status of the button. The other question is what the format in the attr tag means. In fact, format represents the type of the value of this attribute:
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: string. If you want others to directly write a value or use a method similar to "@ string/test" to reference a resource, you can write it as format = "string | reference"
3. Color: Color
4. boolean: boolean Value
5. dimension: dimension value
6. float: float
7. integer: integer
8. fraction: Percentage
9. enum: enumeration. If you provide attributes that can only be selected by others, you can write them as follows:
<Attr name = "language">
<Enum name = "china" value = "1"/>
<Enum name = "English" value = "2"/>
</Attr>
10. flag: bitwise OR operation
Declare-styleable sub-element:
Define a styleable object. Each styleable object is a set of attr attributes. Note: The name attribute here is not necessarily the same as the custom class name, just to distinguish the attributes of the corresponding class.
Note: after the property resource file defines this property, what is the role of this property in terms of which custom View component is used, this attribute resource file is not managed by this attribute resource file. That is to say, this attribute resource file is public and can be used by everyone. However, to facilitate management, generally, all attributes in a custom View are written as a declare-styleable set. what can a property defined by a property resource return? It depends on the Code Implementation of the custom component.
Here, the 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>
Step 2: Get attrs in the custom control class. the values of the attributes defined in the xml file are assigned to the variables that need to be set. Here, the three values are the background image, Slider image, and switch status.
What should we do? We will first
backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.switch_background); slideButton = BitmapFactory.decodeResource(getResources(), R.drawable.slide_button); currentState=false;
Comment out the three sentences and replace them with the following code:
/* Obtain the declare-styleable Set */TypedArray typedArray = context. obtainStyledAttributes (attrs, R. styleable. myToggleButton);/* obtain the total number of attributes in the Set */int indexCount = typedArray. getIndexCount ();/* traverse these attributes, get the id corresponding to the attribute, and then get the corresponding value through the id */for (int I = 0; I <indexCount; I ++) {/* get the corresponding id value taId */int taId = typedArray. getIndex (I); switch (taId) {case R. styleable. myToggleButton_backgroundBitmap: // drawable to 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 (); default: break ;}}
The annotations are also detailed. The basic idea is to first obtain the TypedArray object corresponding to the declare-styleable set corresponding to the MyToggleButton name, and then retrieve the corresponding resources and assign values based on the TypedArray object.
Step 3: Use custom attributes in the layout file and set the attribute values:
<Com. example. myattrsdemo. ui. myView android: layout_width = "wrap_content" android: layout_height = "wrap_content" alex: test_bitmap = "@ drawable/pig" alex: test_id = "1" alex: test_msg = "my custom property instance"/>
In the above Code, we found that we have written a header like alex, which is actually short for the namespace. Therefore, we must add a namespace, see how the Android namespace is written:
xmlns:android="http://schemas.android.com/apk/res/android"
Here xmlns: android inside android, is changeable, here we change to alex, and then for idea "http://schemas.android.com/apk/res/com.example.togglebutton"
Therefore, a complete layout file is written as follows:
<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>
So far, a complete custom attribute process is complete. We can directly modify the three custom attributes in the layout file, so that we can see different effects during running, which is relatively high...
Ii. Use custom attributes without using XML resource files:
Since there is no attrs. xml, there is no need for a namespace. We directly Add the following sentence to the layout file:
Test_text = "test using custom attributes without XML resource files"
Then we can obtain it in java. Here we only do simple printing:
// Namespace test String attributeValue = attrs. getAttributeValue (null, "test_text"); System. out. println (attributeValue );
Running result:
According to this idea, the three attributes defined above can be changed to a namespace-free method, which looks very convenient. But there are drawbacks:
The namespace can be omitted. The attribute name must be properly matched. Otherwise, the program cannot be obtained. It is not subject to the combination of XML resource files.
Now, the custom control trilogy is complete. The custom ViewGroup content will be added later. Thank you for your attention!
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.
Android custom controls inherit views. What are the differences between the three constructor methods of the parent class?
The android developer website has the following instructions:
Public View (Context context) is called when the java code creates a View. If the View is filled with xml, this
Public View (Context context, AttributeSet attrs) is called when the xml file is created but no style is specified.
Public View (Context context, AttributeSet attrs, int defStyle ).