Using custom attrs in styles.xml in android

我的未来我决定 提交于 2021-02-18 12:30:10

问题


I made a custom attribute style as

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EffectsTextView">        
        <attr name="strokeWidth" format="float" />
        <attr name="strokeMiter" format="float" />
        <attr name="strokeColor" format="color" />        
    </declare-styleable>
</resources>

In Layout file, I could use this custom attribute assigning a namespace for this attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:effects="http://schemas.android.com/apk/res-auto/com.base.view.EffectsTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40000000" >

 <com.base.view.EffectsTextView
        android:id="@+id/textView1"
        android:layout_width="290dip"
        android:layout_height="80dip"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="16dip"
        android:gravity="center"
        android:text="SETTINGS"
        android:textSize="44dip"
        android:textStyle="bold"  
        effects:strokeWidth="10"  />    <--- custom tag "effects"

However it was not recognizing this custom tag in styles.xml

<style name="EffectsHeaderTextStyle">
     <item name="effects:strokeWidth">10</item>
</style>

Error: No resource found that matches the given name, effects, though I put the namespace same as I did in RelativeLayout file.

Any ideas? Thanks


回答1:


Change your XML to:

xmlns:effects="http://schemas.android.com/apk/res/com.base.view.EffectsTextView"

And change your style:

<style name="EffectsHeaderTextStyle">
    <item name="strokeWidth">10</item>
</style>

I did something similar with fonts:

https://github.com/androidfu/CodeExamples/tree/master/com.androidfu.CustomFontsDemo




回答2:


Gradle doesn't recommend using the actual package in xmln:.
In Gradle projects, the actual package used in the final APK can vary; for example, you can add a .debug package suffix in one version and not the other. Therefore, you should not hardcode the application package in the resource; instead, use the special namespace http://schemas.android.com/apk/res-auto which will cause the tools to figure out the right namespace for the resource regardless of the actual package used during the build.



来源:https://stackoverflow.com/questions/15824289/using-custom-attrs-in-styles-xml-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!