【问题标题】:How to support "tools:text" in a new custom view ?如何在新的自定义视图中支持“工具:文本”?
【发布时间】:2018-07-25 10:36:58
【问题描述】:

背景

开发人员可以通过多种方式为 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: 属性?

【问题讨论】:

标签: android android-studio android-custom-view


【解决方案1】:

如果您想在自定义视图中使用现有的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

【讨论】:

  • 所以没有图书馆就不可能吗?太糟糕了。但既然你已经涵盖了所有内容,谢谢你。你得到了你的 V 和 +1 的努力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
相关资源
最近更新 更多