【问题标题】:Xamarin android custom view get custom attribute always returns default valueXamarin android自定义视图获取自定义属性始终返回默认值
【发布时间】:2017-06-15 07:38:00
【问题描述】:

我正在 xamarin android 中制作自定义视图。我有这个自定义视图的单独类库项目。

我在 Resources/Values/attrs.xml 中的属性文件如下所示:

<?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>

我用于调试的自定义视图文件如下所示:

我将引用添加到该项目中,并将此视图添加到我的 xaml 文件中以进行如下启动活动:

<?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>

没有编译或运行时错误。此自定义视图显示在我的基础项目启动活动中。即使在调试中,它也会转到我的自定义视图文件中的 setValuesFromXml 方法。但是任何从 IAttribueSet 获取 int、string 或 enum 值的尝试都会返回默认值。但我仍然没有任何错误或异常。

如何从 xml 文件中获取我的自定义属性值?

【问题讨论】:

  • 尝试用xmlns:my="http://schemas.android.com/apk/res-auto"替换xmlns:my="http://schemas.android.com/apk/lib/mycomponents"
  • @g4s8 谢谢!!!有用!!但我不明白为什么。我拼错命名空间?并且 res-auto 会自动检测正确的命名空间?
  • 我已经在这里回答了:stackoverflow.com/a/44562475/1723695
  • 一个问题,您是否从视图中夸大了任何布局?如果是这样,你是怎么做到的?

标签: android xml android-layout xamarin.android android-custom-view


【解决方案1】:

您应该使用xmlns:my="http://schemas.android.com/apk/res-auto" 而不是xmlns:my="http://schemas.android.com/apk/lib/mycomponents"。 res-auto 命名空间自动检测应用程序中声明的所有属性,包括所有库属性。例如。 appcompat 属性也可以通过 res-auto 命名空间访问。


您可能会发现它有帮助:https://stackoverflow.com/a/26692768/1723695

【讨论】:

  • 非常感谢
  • 关于如何从视图中扩展布局的任何想法?
猜你喜欢
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
相关资源
最近更新 更多