Styling Custom Views

I have several custom views in my Android project, and I added the relevant data to the attrs.xml file. And now I can implement my objects through XML. It works great.

How do I style these elements? When I try to use my custom attributes in styles.xml, the error "A resource was not found that matches the specified name:"

To use custom views in regular xml development, I use xmlns: app = "http://schemas.android.com/apk/res/bla.bla.bla". What is suitable for use in styles?

This is what my style looks like now

<style name="Journey_DaySelect_Sunday"> <item name="app:onImage">@drawable/day_sunday_selected</item> <item name="app:offImage">@drawable/day_sunday</item> </style> 
+8
android xml android-custom-view custom-view
source share
3 answers

After a more intensive search on Google, I refused to search for an answer elsewhere and accidentally tried to use the absolute namespace of my generated R file, with which it worked. Let it solve all your problems.

USE APPOINTMENT CONTAINING YOUR R file

 <style name="Journey_DaySelect_Sunday" parent="Journey_DaySelect"> <item name="AppZappy.NIRailAndBus:onImage">@drawable/day_sunday_selected</item> <item name="AppZappy.NIRailAndBus:offImage">@drawable/day_sunday</item> </style> 
+18
source share

For clarification, the element name attribute should be the same as in the attribute attribute attrs.xml declare-styleable + ":" + attribute name.

For example:

attrs.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="com.chuck.norris"> <attr name="actionBarTextColor" format="color"/> </declare-styleable> </resources> 

style.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <style name="myNewStyle"> <item name="android:textColor">#FFFF0000</item> <item name="com.chuck.norris:actionBarTextColor">#ffff0000</item> </style> </resources> 

You can then apply this style to all actions using the theme in your manifest.xml file. Anywhere where there is a custom view that wants to use the "actionBarTextColor" attribute, you can use Java code:

 TypedArray typedArray = context.obtainStyledAttributes(attrSet, R.styleable.com_chuck_norris); COLOR_ACTION_BAR_TEXT = typedArray.getColor(R.styleable.com_chuck_norris_actionBarTextColor, 0xff0000ff); typedArray.recycle(); 

I'm not sure why you cannot just define your schema in the style.xml file as mentioned above, but this is apparently a limitation of style.xml.

+2
source share

try this solution

 <style name="Journey_DaySelect_Sunday"> <item name="onImage">@drawable/day_sunday_selected</item> <item name="offImage">@drawable/day_sunday</item> </style> 

link (Chinese)

if you guys find this useful, I will translate it.

0
source share

All Articles