如何在新的自定义视图中支持 "tools:text"?

How to support "tools:text" in a new custom view ?

背景

开发人员可以通过多种方式为 XML 中的已知视图设置各种 tools: 属性,以便它们仅在编辑模式下(在 IDE 上)出现,而不是在运行时间:

https://developer.android.com/studio/write/tool-attributes#tools_instead_of_android

所以,如果你有一个 TextView,你可以设置 tools:text="hello" ,这将只显示在 IDE.

问题

虽然我使用这个不错的功能已经有一段时间了,但我没有找到有关如何创建此类属性或让我自己的自定义视图支持它们(现有的或新的)的文档。

我试过的

我试图像普通属性一样达到这些属性,但我认为这是不可能的(或者我做错了)。

我很长时间以来就知道,我可以使用 View.isInEditMode 检查 IDE 上的代码是否现在是 运行。但这只是一小步。

问题

  1. 假设我有一个自定义视图,我怎样才能让它支持现有的可能的 tools: 属性?例如,假设我不从 TextView 扩展,但我希望支持 tools:text ,我该怎么做?

  2. 如何为自定义视图创建新的 tools: 属性?

如果您想在自定义视图中使用现有的 tools: 属性,您只需将这些属性添加到您的 <declare-stleable>:

<declare-styleable name="CustomView">
    <!-- This will allow you to use tools:text attribute as well -->
    <attr name="android:text"/>
</declare-styleable>

在您的自定义视图中,您可以获得这样的属性:

a.getText(R.styleable.CustomView_android_text)

现在您可以这样做了:

<com.myapplication.CustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:text="Lorem ipsum"/>

这将允许您在自定义视图中使用标准 tools: 属性。如果您想定义自己的设计时属性,I've written a small library that allows you to do that.