15

我创建了一个带有属性的自定义视图。有没有办法在 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>

4

3 回答 3

6

我的意见是你不能。

这里有一个官方的,虽然旧,页面引用:

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

于 2015-10-27T15:07:23.490 回答
2

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

于 2017-08-04T07:45:36.793 回答
1

我编写了一个小型库,允许您为视图定义设计时属性: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该类而不是直接从 a 访问属性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 已经用另一个库发布了一个答案,允许你这样做。他的实现非常聪明,它允许您使用实际的tools:命名空间而不必复制属性。不幸的是,它与 Android Studio 的自动完成功能不兼容。

于 2018-09-01T19:42:11.533 回答