如何在java和xml中传递自定义组件参数
在 android 中创建自定义组件时,经常会被问到如何创建 attrs 属性并将其传递给构造函数。
通常建议在 java 中创建组件时,只需使用默认构造函数,即
new MyComponent(context);
不要尝试创建 attrs 对象来传递到基于 xml 的自定义组件中常见的重载构造函数。我尝试创建一个 attrs 对象,但它似乎并不容易或根本不可能(没有极其复杂的过程),而且从所有方面来看,这并不是真正需要的。
我的问题是:在 java 中构造自定义组件的最有效方法是什么,该组件传递或设置在使用 xml 扩展组件时本来由 attrs 对象设置的属性?
When creating a custom component in android it is often asked how to create and pass through the attrs property to the constructor.
It is often suggested that when creating a component in java that you simply use the default constructor, i.e.
new MyComponent(context);
rather than attempting to create an attrs object to pass through to the overloaded constructor often seen in xml based custom components. I've tried to create an attrs object and it doesn't seem either easy or at all possible (without an exceedingly complicated process), and by all accounts isn't really required.
My question is then: What is the most efficient way of construction a custom component in java that passes or sets properties that would have otherwise been set by the attrs object when inflating a component using xml?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(全面披露:这个问题是 创建自定义视图 的一个分支)
您可以创建超出从
继承的三个标准构造函数的构造函数View
添加你想要的属性......但我不推荐它。最好遵循与其他组件相同的约定。这将使您的组件尽可能灵活,并防止使用您的组件的开发人员因为您的组件与其他组件不一致而焦头烂额:
1.为每个属性提供 getter 和 setter:
2.在
res/values/attrs.xml
中定义属性,以便可以在 XML 中使用它们。3.提供
View
中的三个标准构造函数。如果您需要从采用
AttributeSet
的构造函数之一中的属性中选取任何内容,您可以这样做。 ..完成所有这些后,您可以以编程方式实例化
MyCompnent
......或通过 XML:
其他资源 - https://developer.android.com/training/custom-views/create-view
(Full disclosure: This question is an offshoot of Creating custom view)
You can create constructors beyond the three standard ones inherited from
View
that add the attributes you want......but I don't recommend it. It's better to follow the same convention as other components. This will make your component as flexible as possible and will prevent developers using your component from tearing their hair out because yours is inconsistent with everything else:
1. Provide getters and setters for each of the attributes:
2. Define the attributes in
res/values/attrs.xml
so they can be used in XML.3. Provide the three standard constructors from
View
.If you need to pick anything out of the attributes in one of the constructors that takes an
AttributeSet
, you can do...With all that done, you can instantiate
MyCompnent
programmatically......or via XML:
Additional Resource - https://developer.android.com/training/custom-views/create-view