gpt4 book ai didi

android - 如何在新的自定义 View 中支持 "tools:text"?

转载 作者:太空狗 更新时间:2023-10-29 16:26:17 26 4
gpt4 key购买 nike

背景

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

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

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

问题

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

我尝试过的

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

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

问题

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

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

最佳答案

如果您想使用现有的 tools:您自定义 View 中的属性,您所要做的就是将这些属性添加到您的 <declare-stleable> :

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

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

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:自定义 View 中的属性。如果您想定义自己的设计时属性,I've written a small library that allows you to do that .

关于android - 如何在新的自定义 View 中支持 "tools:text"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51516811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com