【问题标题】:Android XML Is there a way to use the tool namespace with custom attributes?Android XML 有没有办法使用带有自定义属性的工具命名空间?
【发布时间】:2015-10-27 14:39:38
【问题描述】:

我创建了一个带有属性的自定义视图。有没有办法在 Android Studio 中将这些属性与 android 工具一起使用?

例如:

<MyOwnCoolView
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:padding="3dp"
    tools:dividerAngle="2"/>

attr 文件在哪里:

<resources>
<declare-styleable name="MyOwnCoolView">
    <attr name="dividerAngle" format="float"/>
</declare-styleable>

【问题讨论】:

  • 为什么要使用工具命名空间?您可以使用“schemas.android.com/apk/res-auto”命名空间。
  • 拥有一个有价值的占位符。查看它在设计视图中的外观。稍后在运行时,此视图将获得各种值。
  • 据我所知,设计预览也应该与“schemas.android.com/apk/res-auto”一起使用,请务必在类构造函数中检索值。
  • 当然可以,但是虚拟值也保留在那里以用于发布。使用工具您不必担心“清理”虚拟数据
  • 好吧,我终于明白了 :) 你应该编辑你的问题以明确这一点。如果你设置 tools:dividerAngle 会发生什么?什么都没有?

标签: android android-layout android-view android-xml android-tools-namespace


【解决方案1】:

我一直在寻找同样的东西。决定制作一个允许人们这样做的库。 https://github.com/giljulio/sneakpeek

【讨论】:

    【解决方案2】:

    我编写了一个小型库,允许您为视图定义设计时属性:https://github.com/paulmanta/app-tools-attrs

    首先,您必须在设计时声明您想要的单独属性:

    <declare-styleable name="MyWidget">
        <attr name="title" format="string"/>
        <attr name="tools_title" format="string"/>
    </declare-styleable>
    

    最后,当您初始化自定义视图时,使用AppToolsAttrs 类而不是直接从TypedArray 访问属性:

    AppToolsAttrs.getString(a, isInEditMode(), R.styleable.MyWidget_title, R.styleable.MyWidget_tools_title)
    

    然后您可以像这样使用您的设计时属性:

    <com.myapplication.MyWidget
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tools_title="Lorem ipsum"
        app:title="@string/real_title"/>
    

    Gil already posted an answer 使用允许您执行此操作的不同库。他的实现非常聪明,它允许您使用实际的tools: 命名空间,而无需复制属性。不幸的是,它与 Android Studio 的自动完成功能不兼容。

    【讨论】:

      【解决方案3】:

      我认为你不能。

      有一个官方的,虽然非常旧,页面here引用:

      Designtime 属性只能用于框架资源,不能用于 此时自定义属性。

      【讨论】:

      • 您可以尝试在支持网站上提交功能请求。
      • @RCB,你知道现在还是这样吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2013-10-26
      • 1970-01-01
      相关资源
      最近更新 更多