SoFunction
Updated on 2025-04-08

Solve the problem of getting custom colors in Android custom view

Long time no see, I've been a little busy recently, and I haven't posted an article for a long time. The day before yesterday, a junior student encountered this problem while writing a project, so he wrote an article.

Project scenario:

Android Custom View Set Color in Layout

Question description: The following is the code of my junior

//attrs file <attr name="leftcolor" format="color"/>
 <attr name="rightcolor" format="color"/>
//Java file code, get color int leftcolor=("/apk/res-auto","leftcolor",);
 int rightcolor=("/apk/res-auto","rightcolor",);
//In the layout app:leftcolor="@color/colorPrimary"
 app:rightcolor="#ff0000"

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

analyze:

After writing a demo, there were indeed similar problems. I tried several methods myself but couldn't solve them. So I looked at the following Android source code controls and came up with the solution as follows

Solution:

//attrs file <attr name="leftcolor" format="reference|color"/>
 <attr name="rightcolor" format="reference|color"/>
//java file ---TaiJiView is a custom view name //Get custom properties. TypedArray ta = (attrs, );
 //Get color int leftcolor = (.TaiJiView_leftcolor, );
 int rightcolor=(.TaiJiView_rightcolor, );
 //Recycle ();
//In the layout app:leftcolor="@color/colorPrimary"
 app:rightcolor="#ff0000"

If you search for this article, I hope it can solve your problem.

This is the article about getting custom colors in Android custom view. This is all about this article. For more related Android custom view content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!