Solve the problem that Android customizes view to obtain custom colors in attr

  • 2021-12-11 08:54:12
  • OfStack

Long time no see, recently a little busy, a long time no article, the day before yesterday there was a primary school brother in the process of writing the project encountered this problem, thus writing an article.

Project scenario:

Android Custom View Setting Colors in Layout

Question description: The following is the code of the schoolmate


//attrs Documents 
 <attr name="leftcolor" format="color"/>
 <attr name="rightcolor" format="color"/>
//Java File code, get 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);
// In layout 
 app:leftcolor="@color/colorPrimary"
 app:rightcolor="#ff0000"

Problem: rightcolor can get colors, but left can't. (You can get it by writing # ff0000)

Analysis:

After writing an Demo, there is a similar problem, I tried several ways not to solve, so I saw the following Android source control, the solution is as follows

Solution:


//attrs Documents 
 <attr name="leftcolor" format="reference|color"/>
 <attr name="rightcolor" format="reference|color"/>
//java Documents  ---TaiJiView For custom view Name 
 // Gets a custom property. 
 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TaiJiView);
 // Get color 
 int leftcolor = ta.getColor(R.styleable.TaiJiView_leftcolor, Color.BLACK);
 int rightcolor=ta.getColor(R.styleable.TaiJiView_rightcolor, Color.WHITE);
 // Recycle 
 ta.recycle();
// In layout 
 app:leftcolor="@color/colorPrimary"
 app:rightcolor="#ff0000"

If you find this article, I hope to solve your problem.


Related articles: