gpt4 book ai didi

android - 如何在属性集中获取对另一个 View 的引用 - 类似于相对布局中的 layout_below = "id"?

转载 作者:行者123 更新时间:2023-11-30 05:11:24 24 4
gpt4 key购买 nike

我正在构建自定义 View 。我能够使用 format="reference" 成功获取资源。但是,我现在想将另一个 View 的 id 作为属性传递,并且我希望遵循与相对布局类似的限制。

  1. 这必须是 id 或对 View 的引用 - 而不是 drawablecolor 或任何其他值。
  2. 具有提供的 id 的布局必须存在于当前 XML 文件中。
  3. 我应该能够获得对该 View 的引用,并且应该能够将该 View 传递给其他方法。

例如,在相对布局中,如果您输入 layout_below = "@id+/someid",如果 someid 不合适,则会显示警告或错误。

如何实现,请帮忙。

更新

这就是我定义属性的方式

<attr name="myView" format="reference"/>
<attr name="dimen" format="dimension"/>

这就是我在布局 xml 中定义 View 的方式

....
xmlns:custom="http://schemas.android.com/apk/res-auto"
.....
<myPackage.mycustomView android:id = "@+id/myId"
custom:dimen = "10dp" ///-- this one works fine
custom:myView = "@+id/id_of_another_view_in_xml" //-- I am not able to retrive this view
....
/>

最佳答案

This must be id or reference to a view - not drawable or color or any other value.

当您在 attrs.xml 文件中为 ID 指定自定义 View 的属性时,您只需要 reference 类型即可。

the layout with the id that is supplied must exist inside the current XML file.

当您输入无效 ID 时,您在 Android Studio 中看到的红色警告是 lint 警告。如果 ID 确实存在,只是不在布局文件中,它仍然会编译。

如果你想为你的自定义 View 实现同样的事情,你可能需要 add your own lint rule .

I should be able to get a reference to that view and should be able to pass that view to other methods.

不完全确定你在问什么。一旦您扩充了自定义 View 并从 XML 属性中获取了值,您应该有 ID 引用,然后您可以在自定义 View 中使用它来执行 findViewById。如果这不能回答您的问题,请澄清。

编辑:代码示例,在您的自定义 View 构造函数中:

mIdReference = a.getResourceId(R.styleable.MyCustomView_my_view, 0)
if (mIdReference != 0) {
View subView = findViewById(mIdReference)
}

希望对您有所帮助!

关于android - 如何在属性集中获取对另一个 View 的引用 - 类似于相对布局中的 layout_below = "id"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53679750/

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