This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging
Recently, while preparing for the interview, the blogger began to review the knowledge related to the custom view. It happened that a junior in primary school encountered a problem that he could not get the custom value in the process of writing the custom view, so he wrote an article.
Project Scenario:
The Android custom View sets the color in the layout
Problem description:
Attrs. XML file
<attr name="leftcolor" format="color"/>
<attr name="rightcolor" format="color"/>
Copy the code
Java file code to get the color
int leftcolor=attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","leftcolor",Color.BLACK);
int rightcolor=attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","rightcolor",Color.WHITE);
Copy the code
In the layout file
app:leftcolor="@color/colorPrimary"
app:rightcolor="#ff0000"
Copy the code
Rightcolor can get the color, and left can’t get the color. (Write #ff0000 to get it)
Problem analysis:
After writing a Demo, found that there is indeed a similar problem, the blogger tried several ways to solve, so later choose to see the Android source control, the solution is as follows
Solution:
/ / attrs. XML file
<attr name="leftcolor" format="reference|color"/>
<attr name="rightcolor" format="reference|color"/>
// Java file --TaiJiView for custom view name
// Get custom attributes.
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TaiJiView);
// Get the color
int leftcolor = ta.getColor(R.styleable.TaiJiView_leftcolor, Color.BLACK);
int rightcolor=ta.getColor(R.styleable.TaiJiView_rightcolor, Color.WHITE);
/ / recycling
ta.recycle();
/ / in the layout
app:leftcolor="@color/colorPrimary"
app:rightcolor="#ff0000"
Copy the code
Extensions: Common types of attribute values
Format supports 11 types:
- 1. Reference: Indicates the ID of a resource.
- 2. Color: Color value.
- 3. Boolean: Boolean value.
- 4. Dimension: size value.
- 5. Float: float value.
- 6. Integer: Indicates an integer value.
- 7. String: a string.
- The number of children is a fraction.
- 9. Enum: indicates the enum value.
- 10. Flag: bit or operation.
- 11. Mixed types: Multiple types of values can be specified when a property is defined.
format = "reference|color"
Copy the code
That is the content of this article, welcome to leave a message, if you have questions can be private message.