代码之家  ›  专栏  ›  技术社区  ›  android developer

如何在新的自定义视图中支持“工具:文本”?

  •  0
  • android developer  · 技术社区  · 7 年前

    背景

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

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

    所以,如果你有一个文本视图,你可以设置 tools:text="hello" ,这将仅在IDE中显示。

    问题

    虽然我使用这个好的特性已经有相当长的一段时间了,但是我还没有找到关于如何创建这些属性的文档,或者让我自己的自定义视图支持它们(现有的或新的)。

    我试过什么

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

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

    问题

    1. 如果我有一个自定义视图,我如何使它支持现有的 工具: 属性?例如,假设我不从textview扩展,但我确实希望支持 tools:text ,我该怎么做?

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Paul Manta    7 年前

    如果要使用现有 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"/>
    

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