Understanding the custom properties in Android _android

Source: Internet
Author: User

The examples in this article explain the customization properties in Android, as follows

1. Introduction

For custom attributes, you are certainly not unfamiliar, follow the following steps, you can achieve:

    • Customizing a CustomView (extends View) class
    • Write Values/attrs.xml, where you write tag elements such as styleable and item
    • CustomView using custom attributes in Layout files (note namespace)
    • In the CustomView construction method, the Typedarray is used to obtain

PS: If you are unfamiliar with the above steps, it is advisable to familiarize yourself with the above.
Well, I have a few questions:

    • How did the above steps work?
    • What is the meaning of styleable? Can you not write it? I custom attribute, I declare attribute is good, why must write a styleable?
    • If the system already has a more semantically explicit attribute, can I use it directly?
    • There is a parameter in the construction method called AttributeSet
      (Eg:mytextview (context, AttributeSet attrs)) This parameter looks at the name to know that it contains an array of parameters, so can I get my custom attributes through it?
    • What the hell is Typedarray? Where did you come from, you want me to use it?

Well, in the light of these questions, we can consider how to answer them. Or say: I will recite the above 4 steps is enough ~ ~

2. Common examples

Then, by example to answer the above questions, the answer sequence is uncertain ~ ~ Everyone first look at a common example, that is, the code of several steps above.

Declaration file for custom attributes

  <?xml version= "1.0" encoding= "Utf-8"?>
<resources>

  <declare-styleable name= "Test" >
    <attr name= "Text" format= "string"/>
    <attr name= "testattr" format= "integer"/>
  </ Declare-styleable>

</resources>

Customizing the View class

Package com.example.test;

Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import Android.view.View;

public class Mytextview extends View {

  private static final String TAG = MyTextView.class.getSimpleName ();

  Public Mytextview (context, AttributeSet attrs) {
    Super (context, attrs);

    TypedArray ta = context.obtainstyledattributes (attrs, r.styleable.test);

    String Text = ta.getstring (r.styleable.test_testattr);
    int textattr = Ta.getinteger (R.styleable.test_text,-1);

    LOG.E (TAG, "text =" + text + ", textattr =" + textattr);

    Ta.recycle ();
  }



Used in Layout files

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
  xmlns:tools= "http:// Schemas.android.com/tools "
  xmlns:zhy=" Http://schemas.android.com/apk/res/com.example.test "
  android: Layout_width= "Match_parent"
  android:layout_height= "match_parent" >

  <com.example.test.mytextview
    android:layout_width= "100DP"
    android:layout_height= "200DP"
    zhy:testattr= "520"
    zhy:text= " HelloWorld "/>

</RelativeLayout>

OK, everybody spend 3s sweep, the result of the operation is:

 Mytextview:text = HelloWorld, textattr = 520

Not surprisingly, notice that my styleable name is test, so it's not necessarily a custom view name.

3, AttributeSet and Typedarray

Consider the following:

One of the parameters in the constructor is called AttributeSet (Eg:mytextview (context, AttributeSet attrs). The parameter looks at the name to know that it contains a set of parameters. So can I go through it to get my custom attributes?
First of all, the attributeset is guaranteed to have all the attributes of the view declaration, and the outside can indeed get (custom) properties from it.
In fact, look at the AttributeSet method is clear, the following look at the code.

Public Mytextview (context, AttributeSet attrs) {
    Super (context, attrs);

    int count = Attrs.getattributecount ();
    for (int i = 0; i < count; i++) {
      String attrname = Attrs.getattributename (i);
      String attrval = Attrs.getattributevalue (i);
      LOG.E (TAG, "attrname =" + Attrname + ", Attrval =" + Attrval);
    }

    ==>use Typedarray ...

  }

Output:

Mytextview (4136): Attrname = layout_width, Attrval = 100.0dip
Mytextview (4136): Attrname = layout_height, AttrVal = 200.0dip
Mytextview (4136): Attrname = text, Attrval = HelloWorld mytextview
(4136): Attrname = testattr, attrval = 520

What do you find in combination with the above layout file?
I rub, it's amazing, really get all the attributes, yes, yes, the attributeset can get all the attributes defined in the layout file key and value (there are some ways to try), then is not that typedarray this ghost can be abandoned? The answer is: no!.

Now look at the next question:

What the hell is Typedarray? Where did you come from, you want me to use it?
We simply modify the properties of the Mytextview in the layout file.

<com.example.test.mytextview
    android:layout_width= "@dimen/dp100"
    android:layout_height= "@dimen/ dp200 "
    zhy:testattr=" 520 "
    zhy:text=" @string/hello_world "/>

Now the result of running again is:

Mytextview (4692): Attrname = layout_width, Attrval = @2131165234 mytextview
(4692): Attrname = Layout_height, AttrVal = @2131165235
Mytextview (4692): Attrname = text, Attrval = @2131361809 mytextview
(4692): Attrname = Testattr, a Ttrval = 520
>>use typedarray
mytextview (4692): Text = Hello world!, textattr = 520

What did you find out? The value obtained by AttributeSet, if the reference becomes a string of @+ digits. You know, you can read this thing. Then you look at the last line using the Typedarray to get the value, is not instantaneous understand what.

Typedarray is actually used to simplify our work, such as the previous example, if the value of the property in the layout is a reference type (for example: @dimen/dp100), if you use AttributeSet to get the final pixel value, then you need the first step to get the ID, the second step to resolve the ID. And Typedarray is helping us simplify the process.

To paste: The process of obtaining the final pixel value by AttributeSet:

int widthdimensionid = attrs.getattributeresourcevalue (0,-1);
    LOG.E (TAG, "layout_width=" +getresources (). Getdimension (Widthdimensionid));

OK, now people ask you typedarray the meaning of existence, you can tell him.

4, Declare-styleable

We've solved two problems, and next, let's look at the layout file, and we have a property called: Zhy:text.
It is well known that the system provides a property called: Android:text, then I think the direct use of android:text is better, so, consider the problem:

If the system already has a more semantically explicit attribute, can I use it directly?
The answer is yes, how to do it?
Use the Android:text property directly in Attrs.xml.

<declare-styleable name= "Test" > <attr name= "android:text"/> <attr name= "testattr" format= "
    Integer "/>
  </declare-styleable>

Note that here we use the properties that have already been defined and do not need to add the Format property (note the difference between the declaration and the usage, the difference being whether there is a format).
It is then obtained in the class: Ta.getstring (R.styleable.test_android_text), android:text= "@string/hello_world" directly in the layout file.

To mention here, the attributes defined in the system are actually similar to our custom attributes, and you can see the attributes defined in the system in the Sdk/platforms/android-xx/data/res/values directory. You can then find the code in the system-supplied view (Eg:textview) constructor that Typedarray gets the property (see for yourself).

Ok, next, I was thinking, since the name of declare-styleable this tag can be casually written, so casual, then consider the problem:

What is the meaning of styleable? Can you not write it? I custom attribute, I declare attribute is good, why must write a styleable?
actually can not write, how to do?

First delete the declare-styleable label
So now the Attrs.xml is:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  <attr name= "testattr" format= "integer"/ >
</resources>

* Mytextview Implementation

 package com.example.test;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.util.AttributeSet;
Import Android.util.Log;

Import Android.view.View;

  public class Mytextview extends View {private static final String TAG = MyTextView.class.getSimpleName (); private static final int[] MattR = {Android.
  R.attr.text, r.attr.testattr};
  private static final int attr_android_text = 0;

  private static final int attr_testattr = 1;

    Public Mytextview (context, AttributeSet attrs) {Super (context, attrs);

    ==>use typedarray Typedarray ta = context.obtainstyledattributes (attrs, mattr);
    String Text = ta.getstring (attr_android_text);
    int textattr = Ta.getinteger (attr_testattr,-1); Output Text = Hello world!

    , textattr = 520 LOG.E (TAG, "text =" + text + ", textattr =" + textattr);
  Ta.recycle (); }

}

Looks like a little bit more code, and we can see that we've declared an int array, and the elements in the array are the IDs of the attr we want to get. And based on the position of the element in the array, we define some reshaping constants to represent the subscript, and then get it through Typedarray.
We can see that we were originally:

R.styleable.test => mattr
r.styleable.test_text => attr_android_text (0)
r.styleable.test_testattr = > attr_testattr (1)

So what's the truth? Android would do the same in its own way, and by traditional notation it would generate the following code in R.java:

public static final class attr {public
  static final int testattr=0x7f0100a9;
  }
public static final class Styleable {public
   static final int test_android_text = 0;
   public static final int test_testattr = 1;
   public static final int[] Test = {
      0x0101014f, 0x7f0100a9
    };
  }

OK, according to the above you should find out what. The Styleale system can be written for many constants (int[] arrays, subscript constants, and so on, simplifying our development efforts (think about what code you have to write if a bunch of attributes are written to yourself). Then you must also know the name attribute of declare-styleable, which is usually written in the class name of our custom view. Mainly for intuitive expression, the declare-styleable properties, are used to change view.

In fact, it is useful to understand this principle, see: Android Custom controls gracefully implement the split between elements

OK, now 5 questions, answered 4, first question:

How do several steps of a custom attribute work?
Well, the above and basically covers the answer to this question, everyone summed up their own, so: slightly.

Summarize:

    • The declare-styleable and item,android inside the attrs.xml will make it easier for us to use (AAPT dry) based on the constants generated in R.java. We can not declare declare-styleable just declare the desired attribute.
    • In the view construction method, we can get the value of the custom attribute by AttributeSet, but it is troublesome, and the Typedarray can be conveniently convenient for us to obtain.
    • When we customize view, we can use the properties that the system has already defined.

The above is about the customization of Android attributes related content, I hope to help you learn.

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.