Search code examples
androidxmlandroid-layoutxamarin.androidandroid-custom-view

Xamarin android custom view get custom attribute always returns default value


I am making custom view in xamarin android. I have separate class library project for this custom view.

my attributes file in Resources/Values/attrs.xml looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <declare-styleable name="ImageIconView">
    <attr name="imageIcon" format="integer" />
    <attr name="text" format="string" />
    <attr name="alignment" format="enum">
      <enum name="left" value="0"/>
      <enum name="center" value="1"/>
      <enum name="right" value="2"/>
    </attr>
  </declare-styleable>
</resources>

my custom view file for debugging looks like this:

enter image description here I add the referece to this project and add this view in my xaml file for startup activity like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:my="http://schemas.android.com/apk/lib/mycomponents"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
  <mycomponents.views.ImageIconView
    android:layout_width="match_parent"
    android:layout_height="150dp" 
    my:text="text from xml!!!"
    my:imageIcon="50"
    my:alignment="center"
    />

</LinearLayout>

no compile or runtime erros. This custom view is shown on my base project-s startup activity. Even in debugging it goes to the setValuesFromXml method in my custom view file. But any kind of attempt to get int, string or enum value from IAttribueSet return default value. But still I get no any errors or exceptions.

How shall I get my custom attribute value from xml file?


Solution

  • You should use xmlns:my="http://schemas.android.com/apk/res-auto" instead of xmlns:my="http://schemas.android.com/apk/lib/mycomponents". res-auto namespace automatically detects all attributes declared in you application including all library attributes. E.g. appcompat attributes are also accessible via res-auto namespace.


    You may find it helpful: https://stackoverflow.com/a/26692768/1723695