Android XML有没有办法将工具命名空间与自定义属性一起使用?

时间:2015-10-27 14:39:39

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

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

3 个答案:

答案 0 :(得分:6)

我的意见是你不能。

有一位官员,虽然非常旧,页面here引用:

  

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

答案 1 :(得分:1)

我现在正在寻找同样的事情。决定建立一个允许人们去做的图书馆。 https://github.com/giljulio/sneakpeek

答案 2 :(得分:0)

我编写了一个微型库,该库可让您为视图定义设计时属性: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的自动完成功能不兼容。